Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
Jonathan Solorzano Avatar asked Oct 12 '17 15:10

Jonathan Solorzano


People also ask

How do you round UIView corners?

If you start with a regular UIView it has square corners. You can give it round corners by changing the cornerRadius property of the view's layer . and smaller values give less rounded corners. Both clipsToBounds and masksToBounds are equivalent.

How do you round the corners of the background view in Swift?

Any SwiftUI view can have its corners rounded using the cornerRadius() modifier.

How do you label corner radius in Swift?

"label. layer. masksToBounds = true" is an important code, if you apply corner radius to a label and if it dosen't work than adding this will definitely add the corner radius to a particular label.. So this should be the correct answer..


1 Answers

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

like image 87
Krunal Avatar answered Oct 01 '22 02:10

Krunal