按钮的使用
IOS中 Button(按钮)是用来处理用户的操作。它截取的触摸事件,并发送消息到目标对象。
圆矩形按钮
XIB中的按钮属性
实用程序区(右侧窗口),在属性检查器中,可以在 xib 改变按钮的属性。
按钮类型
-
UIButtonTypeCustom
-
UIButtonTypeRoundedRect
-
UIButtonTypeDetailDisclosure
-
UIButtonTypeInfoLight
-
UIButtonTypeInfoDark
-
UIButtonTypeContactAdd
重要的属性
-
imageView
-
titleLabel
重要的方法
+ (id)buttonWithType:(UIButtonType)buttonType
- (UIImage *)backgroundImageForState:(UIControlState)state
- (UIImage *)imageForState:(UIControlState)state
- (void)setTitle:(NSString *)title forState:(UIControlState)state
- (void)addTarget:(id)target action:(SEL)action forControlEvents: (UIControlEvents) controlEvents
添加一个自定义的方法addDifferentTypesOfButton
-(void)addDifferentTypesOfButton { // A rounded Rect button created by using class method UIButton *roundRectButton = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [roundRectButton setFrame:CGRectMake(60, 50, 200, 40)]; // sets title for the button [roundRectButton setTitle:@"Rounded Rect Button" forState: UIControlStateNormal]; [self.view addSubview:roundRectButton]; UIButton *customButton = [UIButton buttonWithType: UIButtonTypeCustom]; [customButton setBackgroundColor: [UIColor lightGrayColor]]; [customButton setTitleColor:[UIColor blackColor] forState: UIControlStateHighlighted]; //sets background image for normal state [customButton setBackgroundImage:[UIImage imageNamed: @"Button_Default.png"] forState:UIControlStateNormal]; //sets background image for highlighted state [customButton setBackgroundImage:[UIImage imageNamed: @"Button_Highlighted.png"] forState:UIControlStateHighlighted]; [customButton setFrame:CGRectMake(60, 100, 200, 40)]; [customButton setTitle:@"Custom Button" forState:UIControlStateNormal]; [self.view addSubview:customButton]; UIButton *detailDisclosureButton = [UIButton buttonWithType: UIButtonTypeDetailDisclosure]; [detailDisclosureButton setFrame:CGRectMake(60, 150, 200, 40)]; [detailDisclosureButton setTitle:@"Detail disclosure" forState: UIControlStateNormal]; [self.view addSubview:detailDisclosureButton]; UIButton *contactButton = [UIButton buttonWithType: UIButtonTypeContactAdd]; [contactButton setFrame:CGRectMake(60, 200, 200, 40)]; [self.view addSubview:contactButton]; UIButton *infoDarkButton = [UIButton buttonWithType: UIButtonTypeInfoDark]; [infoDarkButton setFrame:CGRectMake(60, 250, 200, 40)]; [self.view addSubview:infoDarkButton]; UIButton *infoLightButton = [UIButton buttonWithType: UIButtonTypeInfoLight]; [infoLightButton setFrame:CGRectMake(60, 300, 200, 40)]; [self.view addSubview:infoLightButton]; }
注:
我们必须添加两个命名为“Button_Default.png” 和 “Button_Highlighted.png”图像,可以通过拖动图片到导航区域。
更新在ViewController.m 中的 viewDidLoad 方法如下
(void)viewDidLoad { [super viewDidLoad]; //The custom method to create our different types of button is called [self addDifferentTypesOfButton]; //Do any additional setup after loading the view, typically from a nib }
输出
现在,当我们运行程序时,我们会得到下面的输出