簡介

按鈕是 iOS 開發中最基礎的 UI 元件之一。使用者可以設置文字或圖片設計按鈕,並搭配所需的按鈕事件來實現畫面部署及功能。本篇文章將提供 **2025 最新語法與最佳實踐**,詳細介紹 UIButton 的使用。

Button 宣告

UIButton 是繼承自 UIControl 的類別,而 UIControl 又是 UIView 的子類別,因此 UIButton 也是 UIView 的一部分。

“`swift
class UIButton: UIControl {}
class UIControl: UIView {}
“`

Button 點擊事件

用戶點擊按鈕時會透過 Target-Action 設計模式來通知你的程式。這種方式不直接處理觸摸事件,而是透過 Interface Builder 連結到你的事件。以下是三種常見的 action 方式:

xib/storyboard 連接事件

“`swift
@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
“`

addTarget 連接事件

“`swift
button.addTarget(self, action: #selector(doSomething), for: .touchUpInside)
“`

“`swift
@objc func doSomething()
@objc func doSomething(sender: UIButton)
@objc func doSomething(sender: UIButton, forEvent event: UIEvent)
“`

Button 常用手勢介紹

UIEvent 中包含幾種手勢點擊模式,這裡是幾個常見的手勢:

touchDragEnter 按住滑進

按住滑進的手勢

touchDragExit 按住滑出

按住滑出的手勢

touchDown 按下事件

按下事件

touchUpInside 按下放開

放開事件

Button Layout 畫面設計

UIButton 的組合由以下幾個元件組成:
– **BackgroundImage**: 背景圖片
– **Image**: 按鈕前方圖片
– **Title**: 顯示文字

UIButton Layout 組成

設置按鈕文字

“`swift
func setTitle(_ title: String?, for state: UIControl.State)
“`

設置按鈕文字顏色

“`swift
func setTitleColor(_ color: UIColor?, for state: UIControl.State)
“`

錯誤排除

若 UIButton 的事件無法觸發,請檢查以下幾點:
1. 確認 button 是否已經添加到視圖中。
2. 確認 button 的 userInteractionEnabled 屬性為 true。
3. 確認 action 方法是否正確連接到 button。

延伸應用

除了基本的使用方式,UIButton 還可以與其他 UI 元件結合使用,例如利用 Autolayout 來實現響應式設計,或者與動畫結合來提升使用者體驗。

Q&A(常見問題解答)

**Q1: UIButton 和 UILabel 有什麼不同?**
A1: UIButton 是一個可互動的按鈕元件,允許用戶點擊,而 UILabel 只是顯示靜態文本,不具互動性。

**Q2: 如何自定義 UIButton 的外觀?**
A2: 你可以使用 setTitle、setImage 和 setBackgroundImage 方法來設置按鈕的文字、圖片和背景圖片,並利用陰影和邊框來進行進一步的美化。

**Q3: UIButton 支援哪些手勢?**
A3: UIButton 支援多種手勢,包括點擊、長按、拖動等,開發者可以根據需要自定義手勢的行為。

Categorized in: