Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีเปลี่ยนสีพื้นหลังปุ่ม (Button Background Color) ใน Swift

เปลี่ยนสีพื้นหลัง UIButton ได้ 2 วิธี: Storyboard และโค้ด

วิธีที่ 1: Storyboard

  1. เลือก UIButton ใน Storyboard
  2. Attributes Inspector → Background → เลือกสี
  3. หรือใช้ Tint Color สำหรับ System Button

วิธีที่ 2: โค้ด (Programmatically)


// UIButton Configuration (iOS 15+ แนะนำ)
var config = UIButton.Configuration.filled()
config.title = "Button Title"
config.baseBackgroundColor = .systemBlue
config.baseForegroundColor = .white
config.cornerStyle = .medium
button.configuration = config

// Legacy Way (iOS 14 หรือก่อน)
button.backgroundColor = .systemBlue
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 8
button.clipsToBounds = true

สีสำหรับ State ต่างๆ (Legacy)


button.setBackgroundColor(.systemBlue, for: .normal)
button.setBackgroundColor(.systemBlue.withAlphaComponent(0.7), for: .highlighted)
button.setBackgroundColor(.systemGray, for: .disabled)

// Extension สำหรับ setBackgroundColor
extension UIButton {
    func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        color.setFill()
        UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(image, for: state)
    }
}

iOS 15+ UIButton.Configuration (Best Practice)


// Primary Button
var primaryConfig = UIButton.Configuration.filled()
primaryConfig.baseBackgroundColor = .systemBlue
primaryConfig.baseForegroundColor = .white

// Secondary Button
var secondaryConfig = UIButton.Configuration.tinted()
secondaryConfig.baseBackgroundColor = .systemBlue
secondaryConfig.baseForegroundColor = .systemBlue

// Borderless
var plainConfig = UIButton.Configuration.plain()
plainConfig.baseForegroundColor = .systemBlue

// ใช้งาน
button.configuration = primaryConfig

Dynamic Color (Dark Mode)


button.backgroundColor = UIColor { traitCollection in
    traitCollection.userInterfaceStyle == .dark ? .systemBlue : .blue
}