Skip to content

Commit 04763b2

Browse files
committed
Add title formatter to support selection styling
1 parent ae6ee19 commit 04763b2

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

HMSegmentedControl/HMSegmentedControl.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88

99
#import <UIKit/UIKit.h>
1010

11+
@class HMSegmentedControl;
12+
1113
typedef void (^IndexChangeBlock)(NSInteger index);
14+
typedef NSAttributedString *(^HMTitleFormatterBlock)(HMSegmentedControl *segmentedControl, NSString *title, BOOL selected);
1215

1316
typedef enum {
1417
HMSegmentedControlSelectionStyleTextWidthStripe, // Indicator width will only be as big as the text width
@@ -40,6 +43,9 @@ typedef enum {
4043

4144
@interface HMSegmentedControl : UIControl
4245

46+
/*
47+
* Array of `NSString` objects
48+
*/
4349
@property (nonatomic, strong) NSArray *sectionTitles;
4450
@property (nonatomic, strong) NSArray *sectionImages;
4551
@property (nonatomic, strong) NSArray *sectionSelectedImages;
@@ -51,6 +57,13 @@ typedef enum {
5157
*/
5258
@property (nonatomic, copy) IndexChangeBlock indexChangeBlock;
5359

60+
/*
61+
* This block is used to apply custom text styling to titles when set.
62+
*
63+
* When this block is provided, no additional styling is applied to the `NSAttributedString` object returned from this block.
64+
*/
65+
@property (nonatomic, copy) HMTitleFormatterBlock titleFormatter;
66+
5467
/*
5568
Text attributes to apply to item title texts.
5669

HMSegmentedControl/HMSegmentedControl.m

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -219,15 +219,13 @@ - (CGSize)measureTitleAtIndex:(NSUInteger)idx {
219219
}
220220

221221
- (NSAttributedString *)attributedTitleAtIndex:(NSUInteger)idx {
222-
id title = self.sectionTitles[idx];
223-
if ([title isKindOfClass:[NSString class]]) {
224-
NSDictionary *titleAttrs = idx == self.selectedSegmentIndex ? [self resultingSelectedTitleTextAttributes] : [self resultingTitleTextAttributes];
222+
NSString *title = self.sectionTitles[idx];
223+
BOOL selected = idx == self.selectedSegmentIndex;
224+
if (self.titleFormatter == nil) {
225+
NSDictionary *titleAttrs = selected ? [self resultingSelectedTitleTextAttributes] : [self resultingTitleTextAttributes];
225226
return [[NSAttributedString alloc] initWithString:(NSString *)title attributes:titleAttrs];
226-
} else if ([title isKindOfClass:[NSAttributedString class]]) {
227-
return (NSAttributedString *)title;
228227
} else {
229-
NSAssert(title == nil, @"Unexpected type of segment title: %@", [title class]);
230-
return nil;
228+
return self.titleFormatter(self, title, selected);
231229
}
232230
}
233231

0 commit comments

Comments
 (0)