[英]Programmatically Setting Corner Radius for UIButtons in Landscape and Portrait Mode for All iPhone and iPad Devices
[英]Dynamic corner Radius for landscape and portrait
在layoutSubviews
方法中設置角半徑。
如果需要圓形視圖,請將角半徑設置為半寬/高。
view.layer.cornerRadius = view.frame.width / 2.0
旋轉時,視圖的大小會發生變化,之前應用的cornerRadius會變得太大。 您必須在layoutSubviews中更新角半徑。 試試這個小班:
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()
}
}
將此類設置為界面構建器中的視圖。 如果您的視圖是方形的,請在界面構建器中將hasSquareCornerRadius檢查為true。
我可以在你的屏幕截圖中看到你提供固定的角半徑
同時使用倍增器為superview提供相等的寬度或高度,這樣當你旋轉UIView的尺寸改變時你得到了這個結果。
當self.layoutSubviews()
方法中的方向發生變化時,您需要重置視圖的角半徑。
您也可以通過編程方式檢查設備是水平還是垂直,然后只需更改角半徑,如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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.