按鈕UIButton是ios開發中最常見的控制項之一,下面來介紹UIButton的詳細內容,及開發中需要注意的問題。
UIButton簡介:
使用目標動作設計模式,target-action模式,3種回調的模式之一。
實現原理:
使用下面的方法封裝,根據使用者的點擊移動等動作
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;建立按鈕:
//構造器方法,調用該方法建立某個樣式的按鈕對象
+ (id)buttonWithType:(UIButtonType)buttonType
參數:
buttonType:按鈕樣式
枚舉值:
UIButtonTypeCustom = 0, 自訂風格UIButtonTypeRoundedRect, 圓角矩形
UIButtonTypeDetailDisclosure, 藍色小箭頭按鈕,主要做詳細說明用
UIButtonTypeInfoLight, 亮色驚嘆號
UIButtonTypeInfoDark, 暗色驚嘆號
UIButtonTypeContactAdd, 十字加號按鈕UIButtonTypeSystem ,系統預設樣式,若使用此樣式,在使用setImage時會顯示異常
樣本:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
配置按鈕標題
//擷取按鈕的標題文字,唯讀屬性
@property(nonatomic, readonly, retain) UILabel *titleLabel,注意請勿直接使用titleLabel來修改title
//返回在某個狀態下,按鈕的標題文字
- (NSString *)titleForState:(UIControlState)state
參數:
state:控制項狀態
枚舉值:
UIControlStateNormal //常規狀態顯現
UIControlStateHighlighted //高亮狀態顯現
UIControlStateDisabled //禁用的狀態才會顯現
UIControlStateSelected //選中狀態 UIControlStateApplication //當應用程式標誌時
UIControlStateReserved //為內部架構預留,可以不管他
傳回值:此狀態下按鈕的標題文字
樣本:
NSString *title = [button titleForState:UIControlStateNormal];
//設定按鈕在某個狀態下的標題文字
- (void)setTitle:(NSString *)title
forState:(UIControlState)state
樣本:
[button setTitle:@"按鈕" forState:UIControlStateNormal];
//返回在某個狀態下,按鈕標題的富文本
- (NSAttributedString *)attributedTitleForState:(UIControlState)state
參數:
state:控制項的狀態
傳回值:富文本
NSAttirbutedString 為富文本,詳情參見NSAttirbutedString文檔
樣本:
NSAttributedString *attributedString = [button attributedTitleForState:UIControlStateNormal];
//設值按鈕在某個狀態下的富文本標題
- (void)setAttributedTitle:(NSAttributedString *)title
forState:(UIControlState)state
//返回按鈕在某個狀態下的標題顏色
- (UIColor *)titleColorForState:(UIControlState)state
參數:
state:狀態
傳回值:顏色
樣本:
UIColor *color = [button titleColorForState:UIControlStateNormal];
//設定按鈕標題的顏色
- (void)setTitleColor:(UIColor *)color
forState:(UIControlState)state
參數:
color:顏色描述對象
state:狀態
樣本:
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//返回某個狀態下按鈕標題的陰影顏色
- (UIColor *)titleShadowColorForState:(UIControlState)state
//設定某個狀態下按鈕標題的陰影顏色
- (void)setTitleShadowColor:(UIColor *)color
forState:(UIControlState)state
參數:
color:顏色描述對象
state:狀態
樣本:
[button setTitleShadowColor:[UIColor grayColor] forState:UIControlStateNormal];
//標題的陰影改變時,按鈕是否高亮顯示。預設為NO
@property(nonatomic) BOOL reversesTitleShadowWhenHighlighted
配置按鈕示範
//按鈕高亮的情況下,映像的顏色是否要加深一點。預設是YES
@property(nonatomic) BOOL adjustsImageWhenHighlighted
//按鈕禁用的情況下,映像的顏色是否要加深一點。預設是YES
@property(nonatomic) BOOL adjustsImageWhenDisabled
//按下按鈕是否會發光。預設是NO
@property(nonatomic) BOOL showsTouchWhenHighlighted
//返回按鈕在某個狀態下的背景圖片
- (UIImage *)backgroundImageForState:(UIControlState)state
參數:
state:狀態
傳回值:背景映像
樣本:
UIImage *image = [button backgroundImageForState:UIControlStateNormal];
//擷取按鈕的填充圖片
- (UIImage *)imageForState:(UIControlState)state
//設定按鈕的背景圖片
- (void)setBackgroundImage:(UIImage *)image
forState:(UIControlState)state
參數:
image:背景圖片
state:狀態
樣本:
[button setBackgroundImage:image forState:UIControlStateNormal];
//設定按鈕的填充圖片
- (void)setImage:(UIImage *)image
forState:(UIControlState)state
配置按鈕邊框效果
//設定按鈕的內部內容(包含按鈕圖片和標題)離按鈕邊緣上下左右的距離。
@property(nonatomic) UIEdgeInsets contentEdgeInsets
結構體:
CGFloat top, left, bottom, right;
四個值,分別是上左下右
//設定按鈕的內部標題離按鈕邊緣上下左右的距離
@property(nonatomic) UIEdgeInsets titleEdgeInsets
//設定按鈕的內部圖片離按鈕邊緣上下左右的距離
@property(nonatomic) UIEdgeInsets imageEdgeInsets
擷取按鈕目前狀態(唯讀)
//擷取按鈕狀態,唯讀屬性
@property(nonatomic, readonly) UIButtonType buttonType
//擷取按鈕當前標題,唯讀屬性
@property(nonatomic, readonly, retain) NSString *currentTitle
//擷取按鈕當前的富文本標題
@property(nonatomic, readonly, retain) NSAttributedString *currentAttributedTitle
//擷取當前標題的顏色
@property(nonatomic, readonly, retain) UIColor *currentTitleColor
//擷取當前標題的陰影顏色
@property(nonatomic, readonly, retain) UIColor *currentTitleShadowColor
//擷取當前按鈕的圖片
@property(nonatomic, readonly, retain) UIImage *currentImage
//擷取當前按鈕的背景圖片
@property(nonatomic, readonly, retain) UIImage *currentBackgroundImage
//擷取當前按鈕的圖片框對象
@property(nonatomic, readonly, retain) UIImageView *imageView
重寫繪製行為
你可以通過子類化按鈕來定製屬於你自己的按鈕類。在子類化的時候你可以重載下面這些方法,這些方法返回CGRect結構,指明了按鈕每一組成部分的邊界。
注意:不要直接調用這些方法, 這些方法是你寫給系統調用的。
//指定背景邊界
- (CGRect)backgroundRectForBounds:(CGRect)bounds
//指定內容邊界
- (CGRect)contentRectForBounds:(CGRect)bounds
//指定文字標題邊界
- (CGRect)titleRectForContentRect:(CGRect)contentRect
//指定按鈕映像邊界
- (CGRect)imageRectForContentRect:(CGRect)contentRect
樣本:
- (CGRect)imageRectForContentRect:(CGRect)bounds{
return CGRectMake(0.0, 0.0, 44, 44);
}
事件
//給按鈕添加點擊事件
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
枚舉值:
UIControlEventTouchDown // 單點觸摸按下事件:使用者點觸螢幕,或者又有新手指落下的時候。
UIControlEventTouchDownRepeat // 多點觸摸按下事件,點觸計數大於1:使用者按下第二、三、或第四根手指的時候。
UIControlEventTouchDragInside // 當一次觸摸在控制項視窗內拖動時。
UIControlEventTouchDragOutside // 當一次觸摸在控制項視窗之外拖動時。
UIControlEventTouchDragEnter // 當一次觸摸從控制項視窗之外拖動到內部時
UIControlEventTouchDragExit // 當一次觸摸從控制項視窗內部拖動到外部時。
UIControlEventTouchUpInside // 所有在控制項之內觸摸抬起事件
UIControlEventTouchUpOutside // 所有在控制項之外觸摸抬起事件(點觸必須開始與控制項內部才會發送通知)。
UIControlEventTouchCancel //所有觸摸取消事件,即一次觸摸因為放上了太多手指而被取消,或者被上鎖或者撥打電話打斷。
UIControlEventValueChanged // 當控制項的值發生改變時,發送通知。用於滑塊、分段控制項、以及其他取值的控制項。你可以配置滑塊控制項何時發送通知,在滑塊被放下時發送,或者在被拖動時發送。
UIControlEventEditingDidBegin // 當文本控制項中開始編輯時發送通知
UIControlEventEditingChanged // 當文本控制項中的文本被改變時發送通知。
UIControlEventEditingDidEnd // 當文本控制項中編輯結束時發送通知。
UIControlEventEditingDidEndOnExit // 當文本控制項內通過按下斷行符號鍵(或等價行為)結束編輯時,發送通知。
UIControlEventAllTouchEvents // 通知所有觸摸事件。
UIControlEventAllEditingEvents // 通知所有關於文本編輯的事件。
UIControlEventApplicationReserved // range available for application use
UIControlEventSystemReserved // range reserved for internal framework use
UIControlEventAllEvents // 通知所有事件
複選框checkBox的實現:
首先給選中,何不選中的時候設定背景圖片
點擊按鈕的時候,取反selected值即可
利用selected狀態,反選即可
範例程式碼:
-(void)checkboxClick:(UIButton *)btn
{
btn.selected = !btn.selected;
}
- (void)viewDidLoad {
UIButton *checkbox = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect checkboxRect = CGRectMake(135,150,36,36);
[checkbox setFrame:checkboxRect];
[checkbox setImage:[UIImage imageNamed:@"checkbox_off.png"] forState:UIControlStateNormal];
[checkbox setImage:[UIImage imageNamed:@"checkbox_on.png"] forState:UIControlStateSelected];
[checkbox addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:checkbox];
}
自由調整表徵圖按鈕中的表徵圖和文字位置(擴充UIButton)
1,Custom類型的UIButton
我們使用定製類型(Custom)的按鈕就可以設定文字前面的表徵圖。但是圖片和文字的相對位置是固定的(按鈕在前,文字在後)。
(1)我們用下面的左圖(64*64)製作一個帶表徵圖的按鈕
//建立一個圖片加文字的按鈕
let btn1:UIButton = UIButton(frame: CGRect(x: 50, y: 50, width: 180, height: 32))
btn1.setImage(UIImage(named: "alert"), forState: UIControlState.Normal) //按鈕表徵圖
btn1.titleLabel?.font = UIFont.boldSystemFontOfSize(28) //文字大小
btn1.setTitle("帶表徵圖按鈕", forState: UIControlState.Normal) //按鈕文字
btn1.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字顏色
self.view.addSubview(btn1)
(2)圖片與文字間的間距方式1 - 設定圖片位移量(imageEdgeInsets)
1
btn1.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
(3)圖片與文字間的間距方式2 - 設定文字位移量(titleEdgeInsets)
btn1.titleEdgeInsets= UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
2,擴充UIButton
如果我們想要把文字和圖片位置調換下(即文字在前、圖片在後),或者文字和圖片改成上下排列,那麼同樣通過設定 titleEdgeInsets 和 imageEdgeInsets 即可實現。
為方便快速的設定圖片和文字的相對位置,以及間距,這裡對UIButton進行擴充。
(1)擴充代碼如下:
import UIKit
extension UIButton {
@objc func set(image anImage: UIImage?, title: String,
titlePosition: UIViewContentMode, additionalSpacing: CGFloat, state: UIControlState){
self.imageView?.contentMode = .Center
self.setImage(anImage, forState: state)
positionLabelRespectToImage(title, position: titlePosition, spacing: additionalSpacing)
self.titleLabel?.contentMode = .Center
self.setTitle(title, forState: state)
}
private func positionLabelRespectToImage(title: String, position: UIViewContentMode,
spacing: CGFloat) {
let imageSize = self.imageRectForContentRect(self.frame)
let titleFont = self.titleLabel?.font!
let titleSize = title.sizeWithAttributes([NSFontAttributeName: titleFont!])
var titleInsets: UIEdgeInsets
var imageInsets: UIEdgeInsets
switch (position){
case .Top:
titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing),
left: -(imageSize.width), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
case .Bottom:
titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing),
left: -(imageSize.width), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
case .Left:
titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0,
right: -(titleSize.width * 2 + spacing))
case .Right:
titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
default:
titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
self.titleEdgeInsets = titleInsets
self.imageEdgeInsets = imageInsets
}
}
(2)使用範例
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let btn1:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
btn1.center = CGPointMake(view.frame.size.width/2, 60)
btn1.titleLabel?.font = UIFont.boldSystemFontOfSize(28) //文字大小
btn1.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字顏色
btn1.set(image: UIImage(named: "alert"), title: "文字在左側", titlePosition: .Left,
additionalSpacing: 10.0, state: .Normal)
view.addSubview(btn1)
let btn2:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
btn2.center = CGPointMake(view.frame.size.width/2, 120)
btn2.titleLabel?.font = UIFont.boldSystemFontOfSize(28) //文字大小
btn2.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字顏色
btn2.set(image: UIImage(named: "alert"), title: "文字在右側", titlePosition: .Right,
additionalSpacing: 10.0, state: .Normal)
view.addSubview(btn2)
let btn3:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 170, height: 70))
btn3.center = CGPointMake(view.frame.size.width/2, 230)
btn3.titleLabel?.font = UIFont.boldSystemFontOfSize(28) //文字大小
btn3.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字顏色
btn3.set(image: UIImage(named: "alert"), title: "文字在上方", titlePosition: .Top,
additionalSpacing: 10.0, state: .Normal)
view.addSubview(btn3)
let btn4:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 170, height: 70))
btn4.center = CGPointMake(view.frame.size.width/2, 290)
btn4.titleLabel?.font = UIFont.boldSystemFontOfSize(28) //文字大小
btn4.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字顏色
btn4.set(image: UIImage(named: "alert"), title: "文字在下方", titlePosition: .Bottom,
additionalSpacing: 10.0, state: .Normal)
view.addSubview(btn4)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}