按下时更改按钮位置

时间:2011-08-21 17:19:53

标签: objective-c uibutton location

我有一个按钮,按下时应该向下移动2个像素,并在按下结束时跳回到原始位置。我已经尝试了touchesBegantouchesEnded,但这些不适用于按钮。我也尝试用IUView交换按钮并在touchesEnded中调用按钮的方法,但在向下移动之前给按钮一个奇怪的延迟。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您是否尝试使用Touch Down和Touch Up活动?尝试在Touch Down上移动按钮位置并在Touch Up(内部和外部)上将其恢复为初始值。

编辑:这是一个代码示例:

- (IBAction)moveButtonDown:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    btn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y + 2, btn.frame.size.width, btn.frame.size.height);
}

- (IBAction)moveButtonUp:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    btn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y - 2, btn.frame.size.width, btn.frame.size.height);
}

将moveButtonDown:分配给按钮“Touch Down”事件,并将moveButtonUp:分配给它的“Touch Up Inside”和“Touch Up Outside”事件。经过测试和工作,至少在这里;)

编辑:谢谢fichek,这是CGRectOffset而不是CGRectMake的解决方案:

- (IBAction)moveButtonDown:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    btn.frame = CGRectOffset(btn.frame, 0, 2);
}

- (IBAction)moveButtonUp:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    btn.frame = CGRectOffset(btn.frame, 0, -2);
}