第八天 按钮控制图像移动《苹果iOS实例编程入门教程》
DAY 08
//iOS SDK 中的 UIButton 控制 UIImageView 移动和大小
运行安装好的 xCode
选择: File->New Project.
从 'New Project' 窗口
选择 : iPhone OS ->Applications-> Single View Application
命名 : 这里命名为 “clickAndMove”
//打开 ViewController.h 文件:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
//创建ImageView
UIImageView *subview;
}
-(void) buttonClicked;
@end
//打开 ViewController.m 文件:
- (void)viewDidLoad {
[super viewDidLoad];
//定义图片的位置和尺寸
subview = [[UIImageView alloc] initWithFrame:CGRectMake(80.0, 130.0, 50.0, 40.0)];
//设定图片名称,myPic.png已经存在,拖放添加图片文件到image项目文件夹中
[subview setImage:[UIImage imageNamed:@"myPic.png"]];
//创建按钮
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//定义按钮的位置和尺寸
[sampleButton setFrame:CGRectMake(25, 50, self.view.bounds.size.width - 50, 50)];
//定义按钮标题
[sampleButton setTitle:@"Click" forState:UIControlStateNormal];
//指定按钮执行的程式“click”
[sampleButton addTarget:self action:@selector(buttonClicked)forControlEvents:UIControlEventTouchUpInside]; //此处不换行
//在 View 中加入按钮 subview
[self.view addSubview:sampleButton];
//在 View 中加入图片 subview
[self.view addSubview:subview];
//使用后释放图片
[subview release];
}
//建立按钮执行的程式“click”
-(void) buttonClicked {
//启用动画移动
[UIImageView beginAnimations:nil context:NULL];
//移动时间2秒
[UIImageView setAnimationDuration:2];
//图片持续移动
[UIImageView setAnimationBeginsFromCurrentState:YES];
//重新定义图片的位置和尺寸,位置
subview.frame = CGRectMake(60.0, 150.0, 200.0, 160.0);
//完成动画移动
[UIImageView commitAnimations];
}
下载今天教程文件: Day08.zip
文章本人经过修改及测试,希望大家多多交流。欢迎转载,但请注明出处,多珍惜别人的劳动成果,谢谢大家。