Reputation: 7032
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:
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?
Upvotes: 12
Views: 22535
Reputation: 1598
This solution is working for me to get rounded UIView in Swift 5
view.layer.cornerRadius = 10;
view.clipsToBounds = true
Upvotes: 2
Reputation: 69
public func RoundFrameBackground(_ aView: UIView!, borderWidth: CGFloat!, cornerRadius: CGFloat!, borderColor: UIColor, backgroundColor: UIColor) {
aView.layer.borderWidth = borderWidth ; aView.layer.borderColor = borderColor.cgColor
aView.backgroundColor = backgroundColor ; aView.clipsToBounds = true
aView.layer.cornerRadius = cornerRadius
}
public func RoundFrameOnly(_ aView: UIView!, cornerRadius: CGFloat!) {
aView.clipsToBounds = true
aView.layer.cornerRadius = cornerRadius
}
use:
RoundFrameBackground(*a view*, borderWidth: 1, cornerRadius: 10, borderColor: UIColor.red, backgroundColor: UIColor.blue)
RoundFrameOnly(*a view*, cornerRadius: 10)
Upvotes: 1
Reputation: 79776
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
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:
Upvotes: 32
Reputation: 834
Your code seems to work fine in Swift 4.0 with a new project. However, if you are using a Storyboard and its set as LaunchScreen too, you won't be able to use custom classes directly there.
In that case just uncheck Use as Launch Screen and you should be able to build again.
Upvotes: 0