เปลี่ยน Border Color และ Border Width ของ UIView ได้ 2 วิธี
วิธีที่ 1: โค้ดโดยตรง
let view = UIView()
view.layer.borderWidth = 2.0
view.layer.borderColor = UIColor.systemBlue.cgColor
view.layer.cornerRadius = 8 // เพิ่มมุมโค้งได้ด้วย
วิธีที่ 2: IBDesignable + IBInspectable (แก้ไขใน Storyboard)
@IBDesignable
class DesignableView: UIView {}
extension UIView {
@IBInspectable var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue }
}
@IBInspectable var borderColor: UIColor? {
get {
guard let cgColor = layer.borderColor else { return nil }
return UIColor(cgColor: cgColor)
}
set { layer.borderColor = newValue?.cgColor }
}
@IBInspectable var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
}
การใช้งานใน Storyboard
- สร้าง UIView ใน Storyboard
- ใน Identity Inspector ตั้ง Custom Class =
DesignableView(หรือ UIView ธรรมดาก็ได้เพราะเป็น Extension) - ไป Attribute Inspector จะเห็น Border Width, Border Color, Corner Radius
- ปรับค่าแล้วดูผลทันทีบน Storyboard (Live Rendering)
หมายเหตุสำคัญ
borderColorต้องใช้CGColor(UIColor.cgColor)@IBDesignableทำให้ Render บน Storyboard ได้ แต่บางครั้ง Xcode Crash → Clean Build Folder- Extension UIView ทำให้ UIView ทุกตัวมี Property เหล่านี้ ใช้ได้ทันที
- Performance: IBDesignable อาจทำให้ Xcode ช้าลงในโปรเจกต์ใหญ่