How to make a simple rounded button in Storyboard?

后端 未结 13 1832
渐次进展
渐次进展 2021-01-29 19:49

I just started learning iOS development, cannot find how to make simple rounded button. I find resources for old versions. Do I need to set a custom background for a button? In

13条回答
  •  梦毁少年i
    2021-01-29 20:16

    As other answer have suggested to perform most of this work in code only one answer actually provided a way to view your changes in the storyboard IB Interface. My answer goes beyond that answer by allowing you to change the cornerRadius of the view, button, image, etc.

    Please take a look at the following code. To use this code create a new swift file called RoundedView or whatever you would like to call it then go to your storyboard and change the class to either "RoundedView", "RoundedImageView" or "RoundedButton".

    import UIKit
    
    @IBDesignable class RoundedImage: UIImageView
    {
        override func layoutSubviews() {
            super.layoutSubviews()
    
            updateCornerRadius()
        }
    
        @IBInspectable var rounded: Bool = false {
            didSet {
                updateCornerRadius()
            }
        }
    
        @IBInspectable var cornerRadius: CGFloat = 0.1 {
            didSet {
                updateCornerRadius()
            }
        }
    
        func updateCornerRadius() {
            layer.cornerRadius = rounded ? cornerRadius : 0
            layer.masksToBounds = rounded ? true : false
        }
    }
    
    @IBDesignable class RoundedView: UIView
    {
        override func layoutSubviews() {
            super.layoutSubviews()
    
            updateCornerRadius()
        }
    
        @IBInspectable var rounded: Bool = false {
            didSet {
                updateCornerRadius()
            }
        }
    
        @IBInspectable var cornerRadius: CGFloat = 0.1 {
            didSet {
                updateCornerRadius()
            }
        }
    
        func updateCornerRadius() {
            layer.cornerRadius = rounded ? cornerRadius : 0
            layer.masksToBounds = rounded ? true : false
        }
    }
    
    @IBDesignable class RoundedButton: UIButton
    {
        override func layoutSubviews() {
            super.layoutSubviews()
    
            updateCornerRadius()
        }
    
        @IBInspectable var rounded: Bool = false {
            didSet {
                updateCornerRadius()
            }
        }
    
        @IBInspectable var cornerRadius: CGFloat = 0.1 {
            didSet {
                updateCornerRadius()
            }
        }
    
        func updateCornerRadius() {
            layer.cornerRadius = rounded ? cornerRadius : 0
            layer.masksToBounds = rounded ? true : false
        }
    }
    

提交回复
热议问题