原理:
1. 用tintColor属性,把整个UISEgmentControl 设置成为透明色.
2. 设置正常状态下的titleTextAttributes.和选中状态下的titleTextAttributes.
#import "SecondViewController.h" #import "Masonry.h" @interface SecondViewController () @property (nonatomic, strong) UISegmentedControl * segmentedControl_one; @end @implementation SecondViewController #pragma mark - 生命周期 #pragma mark viewDidLoad - (void)viewDidLoad { [super viewDidLoad]; [self basicSetting]; [self addSegmentedControl_one]; } #pragma mark - 系统代理 #pragma mark - 点击事件 - (void)segmentedControl_one:(UISegmentedControl *)sender { NSLog(@"index: %ld",(long)sender.selectedSegmentIndex); } #pragma mark - 实现方法 #pragma mark 基本设置 - (void)basicSetting { self.title = @"隐藏边框"; } - (void)addSegmentedControl_one { [self.view addSubview:self.segmentedControl_one]; [self.segmentedControl_one mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(self.view).with.offset(10); make.right.mas_equalTo(self.view).with.offset(-10); make.top.mas_equalTo(self.view).with.offset(30); make.height.mas_equalTo(40); }]; } #pragma mark - setter & getter - (UISegmentedControl *)segmentedControl_one { if (!_segmentedControl_one) { NSArray * array = @[@"第一段",@"第二段",@"第三段",@"第四段"]; self.segmentedControl_one = [[UISegmentedControl alloc] initWithItems:array]; // 去掉颜色,现在整个segment偶看不到,可以相应点击事件 self.segmentedControl_one.tintColor = [UIColor clearColor]; // 正常状态下 NSDictionary * normalTextAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:16.0f],NSForegroundColorAttributeName : [UIColor grayColor]}; [self.segmentedControl_one setTitleTextAttributes:normalTextAttributes forState:UIControlStateNormal]; // 选中状态下 NSDictionary * selctedTextAttributes = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:20.0f],NSForegroundColorAttributeName : [UIColor redColor]}; [self.segmentedControl_one setTitleTextAttributes:selctedTextAttributes forState:UIControlStateSelected]; [self.segmentedControl_one addTarget:self action:@selector(segmentedControl_one:) forControlEvents:UIControlEventValueChanged]; } return _segmentedControl_one; } @end
时间: 2024-12-21 00:01:28