Reputation: 378
I'm having trouble translating this over to 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;
}];
Upvotes: 2
Views: 108
Reputation: 437381
It depends upon how the setTitleFormatter
was implemented. 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. If it has been audited for nullability, then some of those !
will either be ?
or not needed at all.
Upvotes: 2
Reputation: 93141
You only use title
in the block so may as well replace the other 3 parameters with _
, meaning you don't care about them. 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
])
}
Upvotes: 4