前言
在開發(fā)項(xiàng)目當(dāng)中, 我需要用到一組特殊按鈕, 效果如下:
雖然現(xiàn)在 git 上現(xiàn)成的代碼一抓一籮筐, 但是想來貌似我時(shí)間也不怎么值錢, 就加一會(huì)班寫寫看. 編碼思路如下:
分析
立馬能想到的就是自己新建一個(gè) View, 把按鈕一個(gè)一個(gè)放上去, 點(diǎn)擊按鈕觸發(fā)是事件, 移動(dòng)按鈕下的小白線(underLine).
新建的 View 需要暴露的接口有:
- 初始化方法, 需要傳入按鈕標(biāo)題 數(shù)組
(nullable instancetype)initWithItems:(nullable NSArray *)items; - 點(diǎn)擊不同按鈕時(shí), 執(zhí)行 action
(void)addTarget:(nullable id)target action:(nonnull SEL)action;
實(shí)現(xiàn)
主要代碼如下
添加按鈕
- (void)setButtons
{
int i = 0;
for (NSString *titleStr in _items) {
UIButton *button = [[UIButton alloc] init];
button.tag = 1000+i;
[button setTitle:titleStr forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
i++;
}
UIView *underLine = [[UIView alloc] init];
underLine.backgroundColor = [UIColor whiteColor];
underLine.tag = kLUHUnderLineButtonUnderLineTag;
underLine.layer.cornerRadius = kLUHUnderLineButtonUnderLineHeight/2;
[self addSubview:underLine];
}
計(jì)算位置
CGFloat width = CGRectGetWidth(self.frame)/_items.count;
CGFloat height = CGRectGetHeight(self.frame);
for (int i = 0; i < _items.count; i++) {
UIButton *button = (UIButton *)[self viewWithTag:1000+i];
if (button != nil) button.frame = CGRectMake(i*width, 0, width, height);
}
UIView *underLine = [self viewWithTag:kLUHUnderLineButtonUnderLineTag];
CGFloat underLineW = width - 2*kLUHUnderLineButtonUnderLinePadding;
if (underLine != nil) {
underLine.frame = CGRectMake(self.selectedIndex*underLineW + kLUHUnderLineButtonUnderLinePadding, height-kLUHUnderLineButtonUnderLineHeight,
underLineW, kLUHUnderLineButtonUnderLineHeight);
}
按鈕點(diǎn)擊之后
- (void)buttonAction:(UIButton *)button
{
NSInteger index = button.tag-1000;
if (index == self.selectedIndex) return;
self.selectedIndex = index;
if (self.action != nil) {
[self.target performSelectorOnMainThread:self.action withObject:button waitUntilDone:NO];
}
}
附 源碼