【问题标题】:UIView is not roundedUIView 没有四舍五入
【发布时间】:2020-04-03 12:25:12
【问题描述】:

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

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

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

有什么建议吗?

【问题讨论】:

  • 你在用哪种方法cameraImageContainer.rounded()? viewDidLoad?
  • 你的视图的宽度和高度是多少?
  • @Sweeper in viewDidLayoutSubviews
  • @Jkrist 嗯...我原以为它会起作用...尝试将其放入viewDidAppear,或改用bounds.size,或两者兼而有之...
  • @Rob 宽高为 86x86

标签: swift swift5


【解决方案1】:

由于框架可以更改,因此在设置边界时更容易实现圆角半径。试试这个:

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
  }
}

【讨论】:

    【解决方案2】:

    像这样调用viewDidApper中的函数对图像进行四舍五入

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 2012-08-04
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      相关资源
      最近更新 更多