横向和纵向的动态角半径

Dynamic corner Radius for landscape and portrait

我使用@IBInspectable 创建了 UIView Extension 来设置圆角半径,但是当我只是旋转我的设备时它无法正常工作

import UIKit
import Foundation

extension UIView {

@IBInspectable
var cornerRadius: CGFloat {
     get {
        return layer.cornerRadius
     }
     set {
        layer.cornerRadius = newValue
     }
   }
}

我在以下限制条件下拍摄图像视图

当我 运行 应用程序处于纵向模式时,输出将是

但是当我旋转我的设备时它不起作用

旋转时,您的视图大小会发生变化,并且之前应用的 cornerRadius 变得太大。您必须在 layoutSubviews 中更新角半径。试试这个小 class:

open class CircularView: UIView {
    @IBInspectable open var hasSquareCornerRadius: Bool = false {
        didSet {
            update()
        }
    }

    @IBInspectable open var cornerRadius: CGFloat = 0 {
        didSet {
            update()
        }
    }

    public var normalizedCornerRadius: CGFloat {
        return hasSquareCornerRadius ? bounds.height / 2 : cornerRadius
    }

    fileprivate func update() {
        layer.cornerRadius = cornerRadius
    }

    override open func layoutSubviews() {
        super.layoutSubviews()
        update()
    }
}

将此 class 设置为您在界面生成器中的视图。如果您的视图是方形的,请在界面生成器中将 hasSquareCornerRadius 设置为 true。

layoutSubviews方法中设置圆角半径。

如果您需要圆形视图,请将角半径设置为一半 width/height。

view.layer.cornerRadius = view.frame.width / 2.0

您也可以通过编程方式检查设备是水平的还是垂直的,然后像 Lal Krishna 所说的那样改变角半径

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

if ( ([[UIDevice currentDevice] orientation] ==  UIDeviceOrientationPortrait) )
{
view.layer.cornerRadius = view.frame.width / 2.0
}
else if(([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) || ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft))
{
view.layer.cornerRadius = view.frame.width / 2.0
}

我可以在你的屏幕截图中看到你提供了固定的角半径

enter image description here

还使用乘法器为 superview 提供相等的宽度或高度,这样当您旋转 UIView 的尺寸时,您会得到这个结果。

self.layoutSubviews() 方法中方向改变时,您需要重新设置视图的角半径。