来自Objective C的Swift中的完成块

时间:2015-11-06 23:45:36

标签: ios swift

我无法将其转换为Swift。非常感谢任何帮助,谢谢!

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

2 个答案:

答案 0 :(得分:4)

您只能在块中使用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
    ])
}

答案 1 :(得分:2)

这取决于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类缺乏可注释性注释。如果对可空性进行了审核,则其中一些!将为?或根本不需要with open(file_name,'a') as f: pass