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

Cách thay đổi màu viền và độ dày viền của UIView trong Cocoa Touch

Để thay đổi màu viền (border color) và độ dày viền (border width) của UIView, có 2 cách: viết code trực tiếp hoặc tạo extension @IBDesignable/@IBInspectable để chỉnh trên Storyboard.

Phương pháp 1: Viết code

// Giả sử có view tên backView
backView.layer.borderWidth = 5.0  // Độ dày 5 point
backView.layer.borderColor = UIColor(red: 0.09, green: 0, blue: 0.30, alpha: 1).cgColor  // Màu xanh đậm

Cách thay đổi màu viền và độ dày viền của UIView trong Cocoa Touch

Phương pháp 2: Extension @IBDesignable/@IBInspectable (Chỉnh trên 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 }
    }
}

Sau khi thêm extension, chọn bất kỳ UIView nào trên Storyboard, vào Attribute Inspector sẽ thấy 2 thuộc tính mới: Border Width và Border Color. Chỉnh sửa và thấy kết quả real-time (live rendering) trên Storyboard.

Cách thay đổi màu viền và độ dày viền của UIView trong Cocoa Touch

Lợi ích

  • Designer/Dev không cần viết code cho từng view.
  • Thử nghiệm màu, độ dày ngay lập tức.
  • Dễ maintain: thay đổi tập trung ở extension.

Lưu ý: borderColor nhận CGColor, nên chuyển đổi qua UIColor(cgColor:) và .cgColor.