【问题标题】:Rounded corner on UIView not working only in few simulators like iPhone8, iPhone6s, iPhone6s plus, iPhone 6UIView 上的圆角仅适用于 iPhone 8、iPhone 6s、iPhone 6s plus、iPhone 6 等少数模拟器
【发布时间】:2020-10-31 02:09:33
【问题描述】:

我需要在视图的左上角和右上角获得圆角。下面是相同的代码。

let size = CGSize(width: 30, height: 30)
        let bezierPath = UIBezierPath(roundedRect: self.alertView.bounds, byRoundingCorners: [.topRight, .topLeft], cornerRadii: size)
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = self.alertView.bounds
        shapeLayer.path = bezierPath.cgPath
        self.alertView.layer.mask = shapeLayer

这在 iPhone 8 plus 及更高版本的所有模拟器中都可以正常工作。但对于其余的模拟器,如 iPhone 6、iPhone 6 plus 等,代码无法按要求工作。我什至尝试使用多种类型的视图,但它没有按照要求工作。我只在左侧得到圆角,但在右侧没有。下面是不同模拟器的 UIView 截图

iPhone 11(工作正常)

iPhone 8(不按要求工作)

我在这里没有遇到问题。请帮忙!

【问题讨论】:

  • 您使用的是哪个 iOS 版本?
  • 那个角是什么时候创建的?我猜?在根据大小(cf 约束)进行布局之前,您这样做得太早了。
  • 你在哪里称呼这个?
  • stackoverflow.com/questions/48569864/… 例如,这时你应该调用它。
  • @PGDev 我正在使用最新的 iOS 13 版本。

标签: ios swift xcode uiview uibezierpath


【解决方案1】:

试试

let size = CGSize(width: view.frame.size.width * 0.80, height: 30)

let size = CGSize(width: UIScreen.main.bounds.width * 0.065, height: 30)

数字可以改变。这意味着宽度最多为手机屏幕的 80%。

【讨论】:

  • 您为宽度指定了一个常量值。 iPhone 11 相比 iPhone 8 是宽屏的。当你说 30 时,它不会造成麻烦。您可以尝试上面的代码使其动态化。所以它变成了你想要的图像。
【解决方案2】:

我在每台设备上都对此进行了测试。请试试这个:

  let viewSub = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 200, height: 200))

viewSub.backgroundColor = .red
viewSub.center =  self.view.center
self.view.addSubview(viewSub)

let rectShape = CAShapeLayer()
rectShape.bounds = viewSub.frame
rectShape.position = viewSub.center
rectShape.path = UIBezierPath(roundedRect: viewSub.bounds, byRoundingCorners: [ .topRight , .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath

viewSub.layer.backgroundColor = UIColor.red.cgColor
//Here I'm masking the textView's layer with rectShape layer
viewSub.layer.mask = rectShape

【讨论】:

    【解决方案3】:

    viewDidLayoutSubviews() 中添加圆角半径而不是viewDidLoad()

     override func viewDidLayoutSubviews() {
         self.alertView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
         self.alertView.layer.cornerRadius = 10.0
    }
    

    【讨论】:

    • 不要添加重复的答案。
    • 虽然从技术上讲是一个重复的答案,但它确实提供了更多关于在何处添加重要行的详细信息。
    【解决方案4】:

    您为什么不直接使用 maskedCornerscornerRadius 呢?

    self.alertView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    self.alertView.layer.cornerRadius = 10.0
    

    截图:

    【讨论】:

    • 我只想要左上角和右上角的圆角。但是您发送的代码会给我所有四个角的圆角,对吗?
    • @Guest 不,不会。 [.layerMinXMinYCorner, .layerMaxXMinYCorner] 这里有什么意思
    • 此方案适用于ios11以上。此外,它需要 alertView.clipsToBounds = true 才能工作
    • 嘿,这个解决方案工作得非常好......正是我想要的方式。这是一种更好的方法。非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 2015-12-06
    • 2023-03-04
    • 1970-01-01
    • 2017-08-27
    • 2016-06-07
    • 2016-06-19
    相关资源
    最近更新 更多