在現在的Xcode的版本下,控件的創建可以從控件庫里拖進來即可,為了更熟悉手動的創建一個按鈕,下面來用代碼的方式實現一個button按鈕的創建。
創建工程-修改模擬器的屏幕適配-添加代碼
// ViewController.m
// buildButton
//
// Created by 袁躍 on 16/4/24.
// Copyright ? 2016年 iflytek. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
//要顯示一個界面的時候,首先創建這個界面對應的控制器
//控制器創建好以后,接著創建控制器所管理的那個view,當這個view加載完畢以后
//就開始執行viewDidLoad方法
//只要viewDidLoad方法被執行了,就表示控制器所管理的view創建好了
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//動態創建自己的按鈕
//1.創建按鈕(UIButton)
// UIButton *button = [[UIButton alloc] init];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//2.給按鈕設置文字
[button setTitle:@"我要上iPhone" forState:UIControlStateNormal];
//3.設置高亮狀態下的顯示文字和顏色
[button setTitle:@"摸我一下" forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
//4.設置默認狀態下的背景圖片
UIImage *imageNarmal = [UIImage imageNamed:@"btn_01"];
UIImage *imageHighLighted = [UIImage imageNamed:@"btn_02"];
[button setBackgroundImage:imageNarmal forState:UIControlStateNormal];
//5.設置高亮狀態下的背景圖片
[button setBackgroundImage:imageHighLighted forState:UIControlStateHighlighted];
//6.設置按鈕的frame
button.frame = CGRectMake(50, 100, 100, 100);
//把動態創建的按鈕加到控制器所管理的那個view中
[self.view addSubview:button];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

動態創建按鈕.gif