简体   繁体   English

Swift中来自目标C的完成块

[英]Completion block in Swift from Objective C

I'm having trouble translating this over to Swift. 我在将其转换为Swift时遇到麻烦。 Any help is GREATLY appreciated, thank you! 非常感谢您的任何帮助,谢谢!

[segControl setTitleFormatter:^NSAttributedString *(LBCSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
         NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName : [UIColor blueColor]}];
         return attString;
         }];

You only use title in the block so may as well replace the other 3 parameters with _ , meaning you don't care about them. 您仅在块中使用title ,因此也可以用_替换其他3个参数,这意味着您不必关心它们。 Give this a try: 试试看:

segControl.tittleFormater = {_, title, _, _ -> NSAttributedString in
    NSAttributedString(string: title, attributes:[
        NSForegroundColorAttributeName: UIColor.blueColor
    ])
}

Or a longer version, if the compiler complains about ambigous data types: 如果编译器抱怨数据类型不正确,则使用更长的版本:

segControl.tittleFormater = {(segmentedControl: LBCSegmentedControl, title: NSString, index: Int, selected: Bool) -> NSAttributedString in
    NSAttributedString(string: title, attributes:[
        NSForegroundColorAttributeName: UIColor.blueColor
    ])
}

It depends upon how the setTitleFormatter was implemented. 这取决于如何实现setTitleFormatter If it's just a method, you'd do something like: 如果这只是一种方法,则可以执行以下操作:

segControl.setTitleFormatter { (segmentedControl, title, index, selected) -> NSAttributedString! in
    return NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
}

If it was defined as a block property, you'd do something like: 如果将其定义为块属性,则可以执行以下操作:

segControl.titleFormatter = { (segmentedControl, title, index, selected) -> NSAttributedString! in
    return NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
}

Both of the above assume the Objective-C class lacks nullability annotations. 以上两个都假设Objective-C类缺少可空性注释。 If it has been audited for nullability, then some of those ! 如果已对它的可空性进行了审核,那么其中的一些! will either be ? 会是? or not needed at all. 或根本不需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM