gpt4 book ai didi

ios - 将 Swift 便捷初始化程序转换为 Objective-C

转载 作者:行者123 更新时间:2023-11-29 02:06:17 26 4
gpt4 key购买 nike

我需要将以下 convenience 初始化程序从 Swift 转换为 Objective-C

    convenience init(view: UIView, overlapHandler: (CGRect)->()) {
self.init(view: view, handler: { overlap -> () in
overlapHandler(overlap ?? CGRect.nullRect)
})
}

我的第一次尝试是:

-(instancetype) initWithView:(UIView*)view overlapHandler:(Handler)handler
{
Handler overlapHandler = ^(CGRect overlap) {
if (CGRectIsNull(overlap)) {
return;
}
handler(overlap);
};
return [self initWithView:view andHandler:overlapHandler];
}

但它并没有很好地工作,因为我没有看到 Objective-C block 如何接收非可选的 CGRect。

代码的上下文如下:

import UIKit

class KeyboardOverlapNotifier:NSObject {
typealias Handler = (CGRect?) -> ()

let view:UIView
let handler:Handler

init(view:UIView, handler:Handler) {
self.view = view
self.handler = handler
super.init()
beginListening()
}

deinit {
stopListening()
}

func beginListening() {
token = token ?? nc.addObserverForName(UIKeyboardWillChangeFrameNotification,
object:nil, queue:nil, usingBlock:keyboardFrameDidChange)
}

func stopListening() {
if let observer = token {
nc.removeObserver(observer)
token = nil
}
}

private let nc:NSNotificationCenter = NSNotificationCenter.defaultCenter()
private var token:NSObjectProtocol?
}

private extension KeyboardOverlapNotifier {
func keyboardFrameDidChange(notification: NSNotification!) {
let duration = notification.userInfo!
[UIKeyboardAnimationDurationUserInfoKey] as NSTimeInterval

UIView.animateWithDuration(duration,
delay: 0,
options: .BeginFromCurrentState,
animations: {
let keyboard:CGRect = {
let global = (notification.userInfo!
[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
let local = self.view.convertRect(global, fromView: nil)
return local
}()
let overlap = self.view.bounds.rectByIntersecting(keyboard)
self.handler(overlap.nonEmptyOrNil)
},
completion: nil)
}
}

extension KeyboardOverlapNotifier {
convenience init(view: UIView, overlapHandler: (CGRect)->()) {
self.init(view: view, handler: { overlap -> () in
overlapHandler(overlap ?? CGRect.nullRect)
})
}
}

extension CGRect {
var nonEmptyOrNil:CGRect? { return !self.isEmpty ? self : nil }
}

最佳答案

也许这应该有所帮助?我仍然不确定你的问题到底是什么,所以我唯一能提供的就是对每个问题的引用。

闭包是独立的功能 block ,可以在您的代码中传递和使用。 Swift 中的闭包类似于 C 和 Objective-C 中的 block 以及其他编程语言中的 lambda。闭包可以从定义它们的上下文中捕获和存储对任何常量和变量的引用。这被称为关闭这些常量和变量,因此得名“闭包”。 Swift 为您处理捕获的所有内存管理。

Blocks vs Closures

https://www.codefellows.org/blog/writing-completion-blocks-with-closures-in-swift

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

关于ios - 将 Swift 便捷初始化程序转换为 Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29757084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com