how to make Designable UIImage in Swift

后端 未结 1 1413
我在风中等你
我在风中等你 2021-01-07 12:31

I am a beginner. I want to make a swift file that contains a code to make Designable UIImage, so I will not edit the UI element display by coding, just in Interface builder

1条回答
  •  被撕碎了的回忆
    2021-01-07 13:16

    You can't use UIImage as designable because UIImage is not a UIView subclass you need to make designable your UIImageView instead, the UIImage can't be rendered by itself needs a UIImageView to be rendered

    Use this class

    import UIKit
    
    @IBDesignable
    class RoundableImageView: UIImageView {
    
        @IBInspectable var cornerRadius : CGFloat = 0.0{
            didSet{
                self.applyCornerRadius()
            }
        }
    
        @IBInspectable var borderColor : UIColor = UIColor.clear{
            didSet{
                self.applyCornerRadius()
            }
        }
    
        @IBInspectable var borderWidth : Double = 0{
            didSet{
                self.applyCornerRadius()
            }
        }
    
        @IBInspectable var circular : Bool = false{
            didSet{
                self.applyCornerRadius()
            }
        }
    
        func applyCornerRadius()
        {
            if(self.circular) {
                self.layer.cornerRadius = self.bounds.size.height/2
                self.layer.masksToBounds = true
                self.layer.borderColor = self.borderColor.cgColor
                self.layer.borderWidth = CGFloat(self.borderWidth)
            }else {
                self.layer.cornerRadius = cornerRadius
                self.layer.masksToBounds = true
                self.layer.borderColor = self.borderColor.cgColor
                self.layer.borderWidth = CGFloat(self.borderWidth)
            }
        }
    
        override func awakeFromNib() {
            super.awakeFromNib()
            self.applyCornerRadius()
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            applyCornerRadius()
        }
    
    }
    

    0 讨论(0)
提交回复
热议问题