iOS开发:多个按钮点击滑动效果

现在stonryboard中拖入5个按钮加一个View或者Label控件。

在.m文件中拖线关联这5个按钮和View,并创建“状态”和“监听者”
2个变量。代码如下:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@property (weak, nonatomic) IBOutlet UIButton *btn3;
@property (weak, nonatomic) IBOutlet UIButton *btn4;
@property (weak, nonatomic) IBOutlet UIButton *ben5;
@property (weak, nonatomic) IBOutlet UIView *redRect;
@property (nonatomic) BOOL btnState;//监听按钮状态
@property (nonatomic, strong) UIButton *linstenBtn;//监听者

@end

接着在生成的按钮点击事件中添加逻辑,代码如下:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _btn1.selected = YES;
    _linstenBtn = _btn1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 点击事件
- (IBAction)clickBtn:(UIButton *)sender {
    _linstenBtn.selected = NO;
    sender.selected = YES;
    //改变红块的位置
    CGRect btnFrame = sender.frame;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    self.redRect.frame = CGRectMake(btnFrame.origin.x, self.redRect.frame.origin.y, sender.frame.size.width, sender.frame.size.height);
    [UIView commitAnimations];
    //监听状态
    _linstenBtn = sender;
}

@end

实现效果如下:

iOS开发:多个按钮点击滑动效果_第1张图片

你可能感兴趣的:(iOS,苹果开发,app,ios,苹果开发,xcode,ui)