2

我是 Objective C 的新手,我正在尝试使用在运行时创建的 UIButton 和 UIImageView 将 UIImageView 的动画从屏幕上的一个设置位置切换到屏幕上的另一个设置位置。当我按下 UIButton 时,我希望 UIImageView 从一个位置动画到另一个位置,并且 UIButton 的 setBackgroundImage 切换到另一个 imageNamed: 状态。

任何帮助将不胜感激!

// UIImageView - Roof Panel Creation
roofPanel = [[UIImageView alloc]initWithFrame:CGRectMake(300, 400, 400, 400)];
[roofPanel setImage:[UIImage imageNamed:@"roof-panel.png"]];
[self.view addSubview:roofPanel];

// UIButton - Panel Lift Button Creation
panelLiftButton = [[UIButton alloc]initWithFrame:CGRectMake(722, 300, 70, 50)];
[panelLiftButton setImage:[UIImage imageNamed:@"panel-lift-button.png"] forState:UIControlStateNormal];
[self.view addSubview:panelLiftButton];
4

1 回答 1

0

首先欢迎来到 Objective C,你会喜欢用这门伟大的语言编写代码......

您必须将 UIControlStateSelected 的图像设置为 UIButton,然后添加目标(UIButton 的 IBAction),如下面的代码所示...

确保 UIControlStateSelected 和 UIControlStateNormal 的图像必须不同。

    panelLiftButton = [[UIButton alloc]initWithFrame:CGRectMake(722, 300, 70, 50)];
    [panelLiftButton setImage:[UIImage imageNamed:@"panel-lift-button.png"] forState:UIControlStateNormal];
    [panelLiftButton setImage:[UIImage imageNamed:@"panel-lift-button_ON.png"] forState:UIControlStateSelected];
    [panelLiftButton addTarget:self action:@selector(toggleImage:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:panelLiftButton];

然后做一个函数,如......

-(IBAction)toggleImage:(id)sender
{
    UIButton * btn = (UIButton*)sender;
    btn.selected = ! btn.selected;
    if (btn.selected)
    {
        [UIView animateWithDuration:0.3 animations:^{
            [roofPanel setFrame:CGRectMake(0, 0, 400, 400)];//here you can set your desired frame.
        }];
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            [roofPanel setFrame:CGRectMake(300, 400, 400, 400)];//here you can set your original frame.
        }];

    }

}

享受使用 Objective C 编码的乐趣。

于 2013-03-15T10:28:50.830 回答