建立按鈕

功能:
UIButton實作了一個可供觸碰(觸發)的地方,經由螢幕接收事件,發送到目標對象

實作:

[xcode]
CGRect frame = CGRectMake(10, 15, 300, 20);
frame = CGRectMake(10, 25, 300, 50);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@"Click Me!!" forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.tag = 2000;
[button addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
[/xcode]

實作行為:
[xcode]
-(IBAction)buttonClicked:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Action…"
message:@"Button Clicked!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
}
[/xcode]

參考:

屬性 property:
titleLabel 顯示文字
.titleLabel.font 顯示文字字型 [UIFont systemFontOfSize: 12];
.titleLabel.shadowOffset 影子偏移 button.titleLabel.shadowOffset = CGSizeMake (1.0, 0.0);

方法 Method:
buttonWithType: 按鈕樣式
[c]
typedef enum {
UIButtonTypeCustom = 0,
UIButtonTypeRoundedRect,
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd,
} UIButtonType;
[/c]
setTitle:forState: 設定按鈕文字與狀態,預設值為UIControlStateNormal
[c]
enum {
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 << 0,
UIControlStateDisabled = 1 << 1,
UIControlStateSelected = 1 << 2,
UIControlStateApplication = 0x00FF0000,
UIControlStateReserved = 0xFF000000
};
[/c]
setBackgroundImage:forState: 設定按鈕背景圖片與狀態
setImage:forState: 設定按鈕圖片與狀態
setFrame: 設定按鈕框架

父類別 UIView提供:
setBackgroundColor: 設定按鈕背景色
setTag: 設定識別碼

父類別 UIControl提供:
addTarget:action:forControlEvents:設定觸發目標與啟動行為
[c]
enum {
UIControlEventTouchDown = 1 << 0,
UIControlEventTouchDownRepeat = 1 << 1,
UIControlEventTouchDragInside = 1 << 2,
UIControlEventTouchDragOutside = 1 << 3,
UIControlEventTouchDragEnter = 1 << 4,
UIControlEventTouchDragExit = 1 << 5,
UIControlEventTouchUpInside = 1 << 6,
UIControlEventTouchUpOutside = 1 << 7,
UIControlEventTouchCancel = 1 << 8,

UIControlEventValueChanged = 1 << 12,

UIControlEventEditingDidBegin = 1 << 16,
UIControlEventEditingChanged = 1 << 17,
UIControlEventEditingDidEnd = 1 << 18,
UIControlEventEditingDidEndOnExit = 1 << 19,

UIControlEventAllTouchEvents = 0x00000FFF,
UIControlEventAllEditingEvents = 0x000F0000,
UIControlEventApplicationReserved = 0x0F000000,
UIControlEventSystemReserved = 0xF0000000,
UIControlEventAllEvents = 0xFFFFFFFF
};
[/c]

廣告