Cocoa Touch: How To Change UIView's Border Color And Thickness?

后端 未结 14 1058
心在旅途
心在旅途 2020-11-30 16:56

I saw in the inspector that I can change the background color, but I\'d like to also change the border color and thickness, is this possible?

14条回答
  •  醉梦人生
    2020-11-30 17:19

    Xcode 6 update

    Since Xcode's newest version there is a better solution to this:

    With @IBInspectable you can set Attributes directly from within the Attributes Inspector.

    My Custom View @IBInspectable Attributes

    This sets the User Defined Runtime Attributes for you:

    enter image description here

    There are two approaches to set this up:

    Option 1 (with live updating in Storyboard)

    1. Create MyCustomView.
    2. This inherits from UIView.
    3. Set @IBDesignable (this makes the View update live).*
    4. Set your Runtime Attributes (border, etc.) with @IBInspectable
    5. Change your Views Class to MyCustomView
    6. Edit in Attributes Panel and see changes in Storyboard :)

    `

    @IBDesignable
    class MyCustomView: UIView {
        @IBInspectable var cornerRadius: CGFloat = 0 {
            didSet {
                layer.cornerRadius = cornerRadius
                layer.masksToBounds = cornerRadius > 0
            }
        }
        @IBInspectable var borderWidth: CGFloat = 0 {
            didSet {
                layer.borderWidth = borderWidth
            }
        }
        @IBInspectable var borderColor: UIColor? {
            didSet {
                layer.borderColor = borderColor?.CGColor
            }
        }
    }
    

    * @IBDesignable only works when set at the start of class MyCustomView

    Option 2 (not working since Swift 1.2, see comments)

    Extend your UIView Class:

    extension UIView {
        @IBInspectable var cornerRadius: CGFloat = 0 {
            didSet {
                layer.cornerRadius = cornerRadius
                layer.masksToBounds = cornerRadius > 0
            }
        }
        @IBInspectable var borderWidth: CGFloat = 0 {
            didSet {
                layer.borderWidth = borderWidth
            }
        }
        @IBInspectable var borderColor: UIColor? {
            didSet {
                layer.borderColor = borderColor?.CGColor
            }
        }
    }
    

    This way, your default View always has those extra editable fields in Attributes Inspector. Another advantage is that you don't have to change the class to MycustomView every time. However, one drawback to this is that you will only see your changes when you run your app.

提交回复
热议问题