簡體   English   中英

Swift中來自目標C的完成塊

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM