UIbutton作為簡單且頻繁被使用的控件,其地位在整個app開發中不可小視。在IB中使用button相對來說很簡單,很容易上手,但在多視圖開發中button通常會被即時生成,並設置其屬性和功能,即通過代碼生成。如下是我對button的理解。
//創建圓角button
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
//指定button的位置和大小
button.frame = CGRectMake(10, 10, 75, 75);
//給button設置標簽,用來辨別點擊的是哪個button,常用在委托方法中。
button.tag = 0;
//定義按鈕標題
[button setTitle:@"Button Title" forState:UIControlStateNormal];
//定義按鈕標題字體格式
[button.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
//給button添加委托方法,即點擊觸發的事件。
[button addTarget:selfaction:@selector(touchButton1:) forControlEvents :UIControl EventTouchUp Inside];
//給button添加圖片
[button setImage:[UIImageimageNamed:@"blue_bg(2).png"] forState:UIControlStateNormal];
//將button加入視圖當中
[view addSubview:button];
使用技巧:
button不僅可以用來加載圖片還可以加載label來實現特定文本的顯示。
[button addSubview:label];