iosswiftuiviewswift4ibdesignable

Round Corners UIView in Swift 4


In swift 3 I could do something like this to make my UIView corners round:

import UIKit

@IBDesignable
class DesignableView: UIView {
}

extension UIView {

    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
        }
    }
}

And at the storyboard I could simply change this: properties

Currently I'm getting a "Build failed" at the designable, but Idk why. I'm working on swift 4 and Xcode 9.

Why it's not working in swift 4?


Solution

  • I've tried your code and it's working fine with iOS 11.1 & Swift 4.0. (As you have mentioned it shows you an error, but it's not showing me any error)

    @IBDesignable
    class RoundUIView: UIView {
    
        @IBInspectable var borderColor: UIColor = UIColor.white {
            didSet {
                self.layer.borderColor = borderColor.cgColor
            }
        }
    
        @IBInspectable var borderWidth: CGFloat = 2.0 {
            didSet {
                self.layer.borderWidth = borderWidth
            }
        }
    
        @IBInspectable var cornerRadius: CGFloat = 0.0 {
            didSet {
                self.layer.cornerRadius = cornerRadius
            }
        }
    
    }
    

    Here is result

    enter image description here


    Update:
    Even your updated code is working fine, also.

    @IBDesignable
    class DesignableView: UIView {
    }
    
    extension UIView {
    
        @IBInspectable
        var cornerRadius: CGFloat {
            get {
                return layer.cornerRadius
            }
            set {
                layer.cornerRadius = newValue
            }
        }
    }
    

    Here is result for it:

    enter image description here