[英]Completion block in Swift from Objective C
我在将其转换为Swift时遇到麻烦。 非常感谢您的任何帮助,谢谢!
[segControl setTitleFormatter:^NSAttributedString *(LBCSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName : [UIColor blueColor]}];
return attString;
}];
您仅在块中使用title
,因此也可以用_
替换其他3个参数,这意味着您不必关心它们。 试试看:
segControl.tittleFormater = {_, title, _, _ -> NSAttributedString in
NSAttributedString(string: title, attributes:[
NSForegroundColorAttributeName: UIColor.blueColor
])
}
如果编译器抱怨数据类型不正确,则使用更长的版本:
segControl.tittleFormater = {(segmentedControl: LBCSegmentedControl, title: NSString, index: Int, selected: Bool) -> NSAttributedString in
NSAttributedString(string: title, attributes:[
NSForegroundColorAttributeName: UIColor.blueColor
])
}
这取决于如何实现setTitleFormatter
。 如果这只是一种方法,则可以执行以下操作:
segControl.setTitleFormatter { (segmentedControl, title, index, selected) -> NSAttributedString! in
return NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
}
如果将其定义为块属性,则可以执行以下操作:
segControl.titleFormatter = { (segmentedControl, title, index, selected) -> NSAttributedString! in
return NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
}
以上两个都假设Objective-C类缺少可空性注释。 如果已对它的可空性进行了审核,那么其中的一些!
会是?
或根本不需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.