Reputation: 39
this is by UI extension method
extension UIView {
func roundCorners(corners:UIRectCorner, radiusWidth: CGFloat,radiusHeight: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radiusWidth/2, height: radiusHeight/2))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}}
by this extension method i want to make my buttons with round corners with this code on viewdidload
btnRideNow.roundCorners(corners: [.topRight], radiusWidth: btnRideNow.frame.width,radiusHeight: btnRideNow.frame.height )
btnRideLater.roundCorners(corners: [.topLeft], radiusWidth: btnRideLater.frame.width,radiusHeight: btnRideLater.frame.height )
but on iPhone 5 i am getting this result ScreenShot
you can see left button wouldn't render properly but in iPhone 6 this work properly Why?
Upvotes: 1
Views: 844
Reputation:
Here's a simple subclass that works with IB. You should be able to easily adapt it to your needs:
@IBDesignable
public class Button: UIButton {
@IBInspectable public var borderColor:UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
@IBInspectable public var borderWidth:CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius:CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
}
Now if you wish to simply code things, you were given most of the answer. For a complete circle:
view.layer.cornerRadius = view.frame.height / 2
You can use width though, if it's square. But like @Matt says (he's very good), be careful to do this after you have the frame/bounds properly set!
Upvotes: 0
Reputation: 535231
It's all a matter of timing.
If you call roundCorners
too soon, e.g. in viewDidLoad
, the button's frame
and bounds
may not yet have been finalized. But your roundCorners
depends on the bounds
, so if you add the mask and the button is then resized as a result of layout, you will naturally get the wrong result.
Upvotes: 4
Reputation:
If you want round corners you can simple do:
view.layer.cornerRadius
and if you want a border you can do
view.layer.borderWidth
and color
view.layer.borderColor
Upvotes: 1