Ilya
Ilya

Reputation: 141

ObjC block in swift

Can anybody help me to rewrite this code in swift

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

Part of HMSegmentedControl class:

    @interface HMSegmentedControl : UIControl
....
@property (nonatomic, copy) HMTitleFormatterBlock titleFormatter;
....
@end

typedef NSAttributedString *(^HMTitleFormatterBlock)(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected);

My code is:

segmentedControl1.titleFormatter = {(segmentedControl: HMSegmentedControl, title: NSString, index: Int, selected: Bool) -> NSAttributedString in

        }

I get an error: "‘(HMSegmentedControl, NSString, Int, Bool)->NSAttributedString’ is not convertible to ‘HMTitleFormatterBlock'"

Upvotes: 1

Views: 362

Answers (2)

Andrea Bozza
Andrea Bozza

Reputation: 1384

yo do a Mix with swift and Objective-C.

let titleFormatterBlock: HMTitleFormatterBlock = {(control: AnyObject!, title: String!, index: UInt, selected: Bool) -> NSAttributedString in
            let attString = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIColor.blueColor()
                ])
            return attString;
        }
segmentedControl.titleFormatter = titleFormatterBlock

Upvotes: 3

Ilya
Ilya

Reputation: 141

I have understood my mistake

var titleFormatterBlock: HMTitleFormatterBlock = {(control: AnyObject!, title: String!, index: UInt, selected: Bool) -> NSAttributedString in
    NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName : [UIColor blueColor]}];
    return attString;
}
segmentedControl.titleFormatter = titleFormatterBlock

Upvotes: 0

Related Questions