Use Storyboard to mask UIView and give rounded corners?

前端 未结 4 2020
余生分开走
余生分开走 2020-12-23 00:23

Lots of questions like this explain how to programmatically create a mask and provide rounded corners to a UIView.

Is there a way to do it all within Storyboard? Jus

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 00:57

    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.

提交回复
热议问题