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

Cách đổi màu nền Button trong Swift

Để thay đổi màu nền (background color) của UIButton trong iOS, có 2 cách: dùng Storyboard hoặc code.

Phương pháp 1: Storyboard Editor

  1. Kéo Button vào Storyboard, chọn nó.
  2. Vào Attribute Inspector.
  3. Tìm mục Background (hoặc Background Color tùy Xcode version), chọn màu mong muốn.

Phương pháp 2: Code (Programmatically)

Tạo outlet cho button, trong viewDidLoad hoặc viewWillLayoutSubviews:


@IBOutlet weak var myButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    myButton.backgroundColor = UIColor(red: 0.44, green: 0.01, blue: 0.19, alpha: 1.0)
    // Hoặc dùng color literal:
    // myButton.backgroundColor = #colorLiteral(red: 0.439, green: 0.012, blue: 0.192, alpha: 1)
}

Kết quả

Cách đổi màu nền Button trong Swift

Lưu ý quan trọng (iOS 15+)

Từ iOS 15, UIButton dùng Configuration API mới (UIButton.Configuration). Cách cũ backgroundColor vẫn hoạt động nhưng có thể bị ghi đè bởi configuration.

Cách hiện đại (iOS 15+):


var config = UIButton.Configuration.filled()
config.baseBackgroundColor = .systemRed  // Màu nền
config.baseForegroundColor = .white      // Màu chữ/icon
config.title = "Nhấn tôi"
config.cornerStyle = .medium

button.configuration = config

Vẫn dùng backgroundColor (cần set configuration = nil hoặc plain):


button.configuration = nil  // Hoặc .plain()
button.backgroundColor = .systemRed
button.setTitleColor(.white, for: .normal)

Khuyến nghị: Dùng UIButton.Configuration cho project mới (iOS 15+), dễ dàng quản lý state (highlighted, disabled), icon, padding, corner radius.