点击时移动UIButtons

时间:2014-04-03 19:23:17

标签: ios objective-c xcode uibutton cgpoint

所以我有一个UIButtons的可滚动标签栏,我希望点击按钮移动到标签栏的中心。我已经完成了所有设置,但我无法弄清楚如何移动选定的按钮。

目前我可以在我的方法中指定一个特定的按钮,它可以工作,但我需要它才能用于几个按钮。

@property (strong, nonatomic) IBOutlet UIScrollView *tabBarScrollView;

@property (strong, nonatomic) IBOutlet UIButton *btn_1;
@property (strong, nonatomic) IBOutlet UIButton *btn_2;
@property (strong, nonatomic) IBOutlet UIButton *btn_3;
@property (strong, nonatomic) IBOutlet UIButton *btn_4;
@property (strong, nonatomic) IBOutlet UIButton *btn_5;
@property (strong, nonatomic) IBOutlet UIButton *btn_6;
@property (strong, nonatomic) IBOutlet UIButton *btn_7;
@property (strong, nonatomic) IBOutlet UIButton *btn_8;
@property (strong, nonatomic) IBOutlet UIButton *btn_9;

...

- (void) buttonAnimation{
    [UIView animateWithDuration:(TAB_BAR_ANIMATION_TIME / 2) animations:^{
        CGPoint moveToCenter = CGPointMake(self.btn_1.frame.origin.x +130, 0);
        [self.tabBarScrollView setContentOffset:moveToCenter];
    }];
}

对于我的CGPoint moveToCenter,什么是更好的数学解决方案?

2 个答案:

答案 0 :(得分:0)

当您实例化按钮(对于每个按钮)时,您可以执行以下操作:

[button addTarget:self action:@selector(doSomething:) forControlEvents: UIControlEventTouchUpInside];

和:

-(IBAction)doSomething:(id) sender {
     UIButton *btn = (UIButton *)sender;
    [UIView animateWithDuration:(TAB_BAR_ANIMATION_TIME / 2) animations:^{
        CGPoint moveToCenter = CGPointMake(btn.frame.origin.x +130, 0);
        [self.tabBarScrollView setContentOffset:moveToCenter];
    }];
}

答案 1 :(得分:0)

首先应将所有UIButtons连接到 IBAction,然后在按钮上应用动画,调用该动作:

这是一个未经测试的代码,可以给你一个想法:

- (IBAction) buttonAnimation:(id)sender
{
    CGRect screenFrame  = [[UIScreen mainScreen] bounds];
    UIButton *btn = ((UIButton *)sender).frame;
    CGpoint centerpoint = CGPoint((screenFrame.size.width / 2) - btn.size.width / 2, btn.origin.y); 
    [UIView animateWithDuration:(TAB_BAR_ANIMATION_TIME / 2) 
                     animations:^{
        [self.tabBarScrollView setContentOffset:moveToCenter];
    }];
}