#import "ViewController.h"
//导入HMSegmentedControl.h
#import "HMSegmentedControl.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ViewController
//定义一个控件
@property (nonatomic ,strong) HMSegmentedControl *segmentedControl1;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
//导航栏不透明
self.navigationController.navigationBar.translucent = NO;
self.title = @"segmentedControl";
[self createSegmentedControl];
}
//
- (void)createSegmentedControl{
NSArray *arr = @[@"东",@"南",@"西",@"北"];
_segmentedControl1 = [[HMSegmentedControl alloc] initWithSectionTitles:arr];
_segmentedControl1.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
_segmentedControl1.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
//横条宽度
_segmentedControl1.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
//横条出现位置
_segmentedControl1.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
//横条颜色
_segmentedControl1.selectionIndicatorColor = [UIColor orangeColor];
//横条高度
_segmentedControl1.selectionIndicatorHeight = 2.0f;
//分割线verticalDividerEnabled
_segmentedControl1.verticalDividerEnabled = NO;
//初始选择
_segmentedControl1.selectedSegmentIndex = 0;
[_segmentedControl1 setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
return attString;
}];
//添加点击方法
[_segmentedControl1 addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.segmentedControl1];
}
//点击控件的实现方法
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
if (_segmentedControl1.selectedSegmentIndex == 0) {
self.view.backgroundColor = [UIColor yellowColor];
}
if (_segmentedControl1.selectedSegmentIndex == 1) {
self.view.backgroundColor = [UIColor greenColor];
}
if (_segmentedControl1.selectedSegmentIndex == 2) {
self.view.backgroundColor = [UIColor redColor];
}
if (_segmentedControl1.selectedSegmentIndex == 3) {
self.view.backgroundColor = [UIColor blueColor];
}
}
运行结果: