UIView 不是圆的

UIView is not rounded

我有一个小问题,不确定为什么它不起作用。我有一个代码:

func rounded(cornerRadius: CGFloat? = nil) {
    if let cornerRadius = cornerRadius {
        layer.cornerRadius = cornerRadius
    } else {
        layer.cornerRadius = min(frame.size.height, frame.size.width) / 2
    }
    clipsToBounds = true
}

我正在尝试这样使用:

cameraImageContainer.rounded()

cameraImageContainer = UIView

图像不是很圆润,看起来不太好。

有什么建议吗?

像这样在viewDidApper中调用圆角函数

override func viewDidAppear(_ animated: Bool) {
    cameraImageContainer.rounded()
}

因为只有在加载视图后才会设置按钮的框架 如果您想在 viewDidLoad 中调用它,请为 imageView 创建自定义 class 并将其设置在 storybaord

由于框架可以改变,所以在设置边界时更容易实现角半径。试一试:

class CircleView: UIView {
  override var bounds: CGRect {
    didSet {
      self.layer.cornerRadius = min(bounds.size.height, bounds.size.width) / 2
    }
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    self.commonInit()
  }

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

  private func commonInit() {
    clipsToBounds = true
  }
}