【问题标题】:UIImageView inheritance for round corners圆角的 UIImageView 继承
【发布时间】:2018-07-16 18:44:48
【问题描述】:

我在很多地方都使用圆角的个人资料图片。而不是每次都写

 profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2;

我决定创建自己的类来继承 UIImageView。 并在 init 函数中添加角点

class UISlProfileImageView: UIImageView {
    override init(image: UIImage?){
        super.init(image:image)
        roundCorner()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

extension UISlProfileImageView{
    func roundCorner(){
        self.layer.cornerRadius = self.frame.size.width / 8;
        self.clipsToBounds = true
    }
}

问题是,在我在 Storyboard 中将适当的图片更改为 UISlProfileImageView 后,圆形去核器消失了。你能告诉我吗,我做错了什么。我在我的新课程的初始化中设置了一个断点,奇怪的是它并没有停在那里。

【问题讨论】:

    标签: ios swift uiimageview


    【解决方案1】:

    您应该覆盖方法 layoutSubviews() 并在该方法内调用 roundCorner()。比如

    override func layoutSubviews() {
        super.layoutSubviews()
    
        roundCorner()
    }
    

    【讨论】:

      【解决方案2】:

      如果您想选择对每个 UIImageView 进行舍入,可以将此代码复制到您的项目中,而不会忘记检查 clip to bounds 并将其值设置为 true

      import UIKit
      
      @IBDesignable
      extension UIImageView
      {
          private struct AssociatedKey
          {
              static var rounded = "UIImageView.rounded"
          }
      
          @IBInspectable var rounded: Bool
          {
              get
              {
                  if let rounded = objc_getAssociatedObject(self, &AssociatedKey.rounded) as? Bool
                  {
                      return rounded
                  }
                  else
                  {
                      return false
                  }
              }
              set
              {
                  objc_setAssociatedObject(self, &AssociatedKey.rounded, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                  layer.cornerRadius = CGFloat(newValue ? 1.0 : 0.0)*min(bounds.width, bounds.height)/2
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-29
        • 1970-01-01
        • 2015-11-02
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多