#import "ViewController.h"
@interface ViewController ()
{
UIImageView *_imageView;
UIButton *_button;
// 定义按钮的状态的变量
int state;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 设置按钮的状态为0
state = 0;
// 初始化一个图片对象,加载本地图片
UIImage *image = [UIImage imageNamed:@"001.png"];
// 初始化图片视图
_imageView = [[UIImageView alloc] initWithImage:image];
// 设置图片视图的位置、大小
_imageView.frame = CGRectMake(100, 300, 80, 80);
// 将图片视图添加到view上
[self.view addSubview:_imageView];
// 设置按钮类型
_button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 设置按钮位置、大小
_button.frame = CGRectMake(30, 400, 200, 40);
// 设置按钮标题和按钮状态
[_button setTitle:@"升国旗" forState:UIControlStateNormal];
// 为按钮点击事件绑定一个动作方法,UIControlEventTouchUpInside表示按钮的点击事件
[_button addTarget:self action:@selector(pressBtn) forControlEvents:UIControlEventTouchUpInside];
// 将按钮添加到view上
[self.view addSubview:_button];
}
- (void)pressBtn {
// 判断按钮的状态
if (state == 0) {
//duration为动画持续的时间, animations为动画效果的代码块。
[UIView animateWithDuration:3 animations:^{
_imageView.frame = CGRectMake(100, 30, 80, 80);
}];
// 修改按钮的标签
[_button setTitle:@"降国旗" forState:UIControlStateNormal];
state = 1;
}
else {
[UIView animateWithDuration:3 animations:^{
_imageView.frame = CGRectMake(100, 300, 80, 80);
}];
[_button setTitle:@"升国旗" forState:UIControlStateNormal];
state = 0;
}
}
@end
移动的图片:
效果图: