UIButton 是 iOS 中最常用的互動元件之一。它可以顯示標題、背景圖片、圖示,也能綁定多種觸控事件。以下整理常見建立方式與設定技巧。
UIButton *button =
[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(20, 20, 280, 40);
[button setTitle:@"點擊" forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
[self.view addSubview:button];
[button setTitle:@"確定" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"icon.png"]
forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"background.png"]
forState:UIControlStateHighlighted];
[button addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
有一個常見錯誤是先用 alloc 建立 UIButton,再用 buttonWithType 覆寫,這會導致原本的 frame 資訊遺失,也可能造成記憶體管理問題。建議直接使用 buttonWithType 建立,再設定 frame。
另外,可透過 adjustsImageWhenHighlighted、adjustsImageWhenDisabled 與 showsTouchWhenHighlighted 等屬性,細調按鈕在高亮、停用與觸控時的外觀行為。