使用故事板掩盖 UIView 和给圆角?

很多问题 像这样解释了如何通过编程创建掩码并为 UIView 提供圆角。

有没有一种方法可以在故事板中完成这一切?只是问一下,因为在情节串连板中创建圆角似乎可以更清楚地区分表示和逻辑。

110158 次浏览

You can do it in a storyboard by using user-defined properties. Select the view that you want to round and open its Identity Inspector. In the User Defined Runtime Attributes section, add the following two entries:

  • Key Path: layer.cornerRadius, Type: Number, Value: (whatever radius you want)
  • Key Path: layer.masksToBounds, Type: Boolean, Value: checked

You may have to import QuartzKit in your view's corresponding class file (if any), but I swear that I've gotten it to work without doing that. Your results may vary.

EDIT: Example of a dynamic radius

extension UIView {


/// The ratio (from 0.0 to 1.0, inclusive) of the view's corner radius
/// to its width. For example, a 50% radius would be specified with
/// `cornerRadiusRatio = 0.5`.
@IBDesignable public var cornerRadiusRatio: CGFloat {
get {
return layer.cornerRadius / frame.width
}


set {
// Make sure that it's between 0.0 and 1.0. If not, restrict it
// to that range.
let normalizedRatio = max(0.0, min(1.0, newValue))
layer.cornerRadius = frame.width * normalizedRatio
}
}


}

I verified that this works in a playground.

Yes, I use that a lot but question like this was already answered many times.

But anyway in Interface Builder. You need to add User Defined Runtime Attributes like this:

layer.masksToBounds Boolean YES
layer.cornerRadius Number {View's Width/2}

enter image description here

and enable

Clips subviews

enter image description here

Results:

enter image description here

Use IBInspectable to add the properties to the Storyboard:

you changed Corner Rediuse , Border Widthe and Border Color  also Using StoryBord

extension UIView {
    

@IBInspectable var cornerRadiusV: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
    

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

@IBInspectable var borderColorV: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
}

Even after making all changes in storyboard, Woraphot's answer doesn't work for me.

This worked for me :

layer.cornerRadius = 10
layer.borderWidth = 1
layer.borderColor = UIColor.blue.cgColor

Long answer :

Rounded Corners of UIView/UIButton etc

customUIView.layer.cornerRadius = 10

Border Thickness

pcustomUIView.layer.borderWidth = 1

Border Color

customUIView.layer.borderColor = UIColor.blue.cgColor

You have to connect your view to your code file and then

yourView.layer.cornerRadius = yourView.frame.width / 2
yourView.layer.masksToBounds = true