最近做项目 需求如图 一个UISegmentedControl 没有圆角 没有中间线
先贴代码再分析一下
#import "ScanRecordController.h"
@interface ScanRecordController ()
@property (nonatomic, strong) UISegmentedControl *segmentCtrl;
@end
@implementation ScanRecordController
- (void)viewDidLoad {
[super viewDidLoad];
[self initUI];
}
- (void)initUI{
UILabel *scanLabel = [[UILabel alloc]init];
scanLabel.text = @"扫描记录统计";
scanLabel.font = [UIFont boldSystemFontOfSize:17];
scanLabel.textColor = [UIColor lightGrayColor];
scanLabel.textAlignment = NSTextAlignmentCenter;
scanLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
scanLabel.layer.borderWidth = 2.0f;
scanLabel.frame = CGRectMake(SCREEN_WIDTH/2-75, 10, 150, 40);
[self.view addSubview:scanLabel];
/*********************************************************************/
_segmentCtrl = [[UISegmentedControl alloc] initWithItems:@[@"今天",@"昨天",@"前天"]];
[_segmentCtrl setFrame:CGRectMake(0, scanLabel.bottom+10, SCREEN_WIDTH, 44)];
_segmentCtrl.backgroundColor = [UIColor whiteColor];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName,[UIFont systemFontOfSize:14],NSFontAttributeName,nil];
[_segmentCtrl setTitleTextAttributes:dic forState:UIControlStateNormal];
[_segmentCtrl addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
_segmentCtrl.layer.borderWidth = 5;
_segmentCtrl.layer.borderColor = [UIColor whiteColor].CGColor;
_segmentCtrl.tintColor = RGB(56, 164, 227);
_segmentCtrl.selectedSegmentIndex = 0;
[_segmentCtrl setDividerImage:[UIImage imageNamed:@"31"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.view addSubview:_segmentCtrl];
}
- (void)change:(UISegmentedControl *)seg{
}
@end
1、
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName,[UIFont systemFontOfSize:14],NSFontAttributeName,nil];
[_segmentCtrl setTitleTextAttributes:dic forState:UIControlStateNormal];
这个方法是设置里面的文字为黑色 昨天 今天 明天 黑色的
2、
_segmentCtrl.layer.borderWidth = 5;
_segmentCtrl.layer.borderColor = [UIColor whiteColor].CGColor;
这个方法是用来去掉圆角的 因圆角最多也就5个像素 给他加一个边框 (注:因为我这里的背景是白色的 所以加了白色边框 看起来也就没有了,等会看下面截图就知道了)
3、
_segmentCtrl.selectedSegmentIndex = 0;
这个方法大家都知道了 这是默认点击的是第0个按钮 也就是今天
4、
[_segmentCtrl setDividerImage:[UIImage imageNamed:@"31"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
这个方法是去掉中间的竖线(也叫自定制竖线吧) 其中[UIImage imageNamed:@"31"]是我自己截图的 高度为44 长度为2 白色的 (跟背景色一样 这样就会感觉没有中间竖线了)5、我的截图如下
说明一下 图2 是我点击中间的 昨天 然后把按钮移到 今天 目的是为了让大家看的更清晰