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

วิธีเปลี่ยนสีและความหนาขอบ (Border) ของ UIView ใน Cocoa Touch

เปลี่ยน 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

  1. สร้าง UIView ใน Storyboard
  2. ใน Identity Inspector ตั้ง Custom Class = DesignableView (หรือ UIView ธรรมดาก็ได้เพราะเป็น Extension)
  3. ไป Attribute Inspector จะเห็น Border Width, Border Color, Corner Radius
  4. ปรับค่าแล้วดูผลทันทีบน Storyboard (Live Rendering)

หมายเหตุสำคัญ

  • borderColor ต้องใช้ CGColor (UIColor.cgColor)
  • @IBDesignable ทำให้ Render บน Storyboard ได้ แต่บางครั้ง Xcode Crash → Clean Build Folder
  • Extension UIView ทำให้ UIView ทุกตัวมี Property เหล่านี้ ใช้ได้ทันที
  • Performance: IBDesignable อาจทำให้ Xcode ช้าลงในโปรเจกต์ใหญ่