Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách đổi màu Button khi được nhấn (clicked) trong iOS

Ví dụ: Nhấn nút "Stop" → màu nút chuyển sang đỏ. Đây là pattern phổ biến cho feedback người dùng.

Cách thực hiện

Bước 1: Tạo dự án

Xcode → Single View App → Tên: "ChangeButtonColor".

Bước 2: Thiết lập Storyboard

Mở Main.storyboard → Thêm Button, đặt title "Stop" → Tạo @IBOutlet (btnBgColor) và @IBAction (btnChangeBgColor) cho cùng button.

Cách đổi màu Button khi được nhấn (clicked) trong iOS

Bước 3: Code đổi màu trong Action


@IBAction func btnChangeBgColor(_ sender: Any) {
    self.btnBgColor.backgroundColor = UIColor.red
}

Bước 4: Chạy app

Nhấn button → Màu nền chuyển sang đỏ.

Cách đổi màu Button khi được nhấn (clicked) trong iOS

Các cách nâng cao hơn

1. Đổi màu tạm thời khi nhấn (Highlighted state) - Khuyên dùng

Dùng setBackgroundColor cho các state thay vì đổi cứng trong action:


override func viewDidLoad() {
    super.viewDidLoad()
    
    // Màu bình thường
    button.setBackgroundColor(UIColor.systemBlue, for: .normal)
    // Màu khi nhấn (highlighted)
    button.setBackgroundColor(UIColor.systemBlue.darker(), for: .highlighted)
    // Màu khi disable
    button.setBackgroundColor(UIColor.systemGray, for: .disabled)
}

// Extension helper
extension UIButton {
    func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(image, for: state)
    }
}

extension UIColor {
    func darker(by percentage: CGFloat = 0.2) -> UIColor {
        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        return UIColor(red: min(r - percentage, 1.0), green: min(g - percentage, 1.0), blue: min(b - percentage, 1.0), alpha: a)
    }
}

2. Toggle màu (bật/tắt)


@IBAction func btnChangeBgColor(_ sender: UIButton) {
    sender.isSelected.toggle()
    sender.backgroundColor = sender.isSelected ? .red : .systemBlue
}

3. Animation mượt mà


@IBAction func btnChangeBgColor(_ sender: UIButton) {
    UIView.animate(withDuration: 0.2) {
        sender.backgroundColor = .red
    }
    
    // Hoặc toggle với animation
    UIView.animate(withDuration: 0.3) {
        sender.backgroundColor = sender.backgroundColor == .red ? .systemBlue : .red
    }
}

4. Sử dụng Configuration (iOS 15+)


var config = UIButton.Configuration.filled()
config.baseBackgroundColor = .systemBlue
config.background.backgroundColorTransformer = UIConfigurationColorTransformer { incoming in
    switch incoming {
    case .highlighted: return .systemRed
    case .disabled: return .systemGray
    default: return incoming
    }
}
button.configuration = config

So sánh

Cách Dùng khi
Set backgroundColor trong @IBAction Thay đổi vĩnh viễn sau action (toggle, confirm)
setBackgroundColor(for: .highlighted) Feedback tức thì khi nhấn (mặc định iOS behavior)
UIButton.Configuration (iOS 15+) App mới, muốn declarative, hỗ trợ state tự động