今天又到学习的时间了,我们来学习下UIButton的用法。和昨天一样我们先把main函数去掉,只留下AppDelegate,先创建一个窗口。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
//调用下面2个方法
[self createButton];
[self createButton1];
return YES;
}
然后创建UIButton
-(void)createButton
{
//创建一个 UIButton 按钮,类型为系统默认(UIButtonTypeSystem)
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
//设置按钮范围
btn.frame = CGRectMake(100, 100, 80, 80);
//设置按钮文字颜色
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//设置按钮文字
[btn setTitle:@"下页" forState:UIControlStateNormal];
//设置高亮状态的文字(高亮状态就是你按下去就能看到的状态,比如我点击下页,就会显示出点击按钮这四个字)
[btn setTitle:@"点击按钮" forState:UIControlStateHighlighted];
//把按钮添加到窗口
[self.window addSubview:btn];
}
-(void)createButton1
{
//自定义UIButton用UIButtonTypeCustom方法。还有几个方法可以command点击进去看。
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
btn1.frame = CGRectMake(100, 200, 80, 80);
//设置显示图片
UIImage *image = [UIImage imageNamed:@"Blocks.png"];//图片可以根据自己的需求定制(把图片文件导入到工程中来,这个怎么导入呢?先右击工程,点击ADD Files to)
[btn1 setImage:image forState:UIControlStateNormal];
//设置图片背景高亮状态
UIImage *bgimage = [UIImage imageNamed:@"MathGraph.png"];//设置点击按钮时的背景效果图
[btn1 setImage:bgimage forState:UIControlStateHighlighted];
[self.window addSubview:btn1];
}
下面时代码和效果图,大家可以跟着练习下。