关于iOS

按钮下划线动画移动

2016-08-31  本文已影响68人  安然slience

很多时候我们需要实现在点击按钮的时候,按钮下方的下划线跟着动画移动的效果,可能刚入门的同学写起来有点费劲,在此总结了一点想法,简单易懂,希望可以帮助到你们,如果有更好的建议或者意见,请及时告诉我,相互学习.

- (void)viewDidLoad {
 [super viewDidLoad];

self.view.backgroundColor = [UIColor whiteColor];
self.title = @"动画";
self.navigationController.navigationBar.barTintColor = [UIColor purpleColor];
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setTitleTextAttributes:
 @{NSFontAttributeName:[UIFont systemFontOfSize:19],
   NSForegroundColorAttributeName:[UIColor redColor]}];
[self setBackBarButtonItemWithTitle:@"返回"];

//创建四个按钮及按钮下划线
[self setupBtns];

}

-(void)setupBtns {
UIButton *btn;
for (int i = 0; i < 4; i++) {
    btn = [[UIButton alloc] initWithFrame:CGRectMake(i * (SCREEN_WIDTH/4), 0, SCREEN_WIDTH/4, 40)];
    btn.tag = i;
    btn.backgroundColor = [UIColor lightGrayColor];
    [btn setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
  }

UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(btn.frame), SCREEN_WIDTH/4, 2)];
line.backgroundColor = [UIColor greenColor];
[self.view addSubview:line];
self.line = line;

}

-(void)clickBtn:(UIButton *)sender {
//获取到点击的是哪一个按钮
NSInteger index = [sender.superview.subviews indexOfObject:sender];
[UIView animateWithDuration:0.25 animations:^{//重写下划线的frame
    CGRect frame = self.line.frame;
    frame.origin.x = SCREEN_WIDTH/4 * index;
    self.line.frame = frame;
}];

if (sender.tag == 0) {
    NSLog(@"第一个");
}else if (sender.tag == 1) {
    NSLog(@"第二个");
}else if (sender.tag == 2) {
    NSLog(@"第三个");
}else if (sender.tag == 3) {
    NSLog(@"第四个");
}
}

/**
 *  设置返回按钮标题
 */
- (void)setBackBarButtonItemWithTitle:(NSString *)title
{
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
[btn setTitle:title forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTitleColor:COLOR_MY_WHITE forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
[btn setContentMode:UIViewContentModeScaleAspectFill];
[btn setImageEdgeInsets:UIEdgeInsetsMake(0, -7, 0, 50)];
[btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 10)];
[btn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = barButtonItem;
}

/**
 *  返回按钮点击事件
 */
- (void)backAction:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
上一篇 下一篇

猜你喜欢

热点阅读