很多時候我們需要實現(xiàn)在點擊按鈕的時候,按鈕下方的下劃線跟著動畫移動的效果,可能剛入門的同學寫起來有點費勁,在此總結了一點想法,簡單易懂,希望可以幫助到你們,如果有更好的建議或者意見,請及時告訴我,相互學習.
- (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:@"返回"];
//創(chuàng)建四個按鈕及按鈕下劃線
[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];
}