簡體   English   中英

動態角半徑為景觀和肖像

[英]Dynamic corner Radius for landscape and portrait

我使用@IBInspectable創建UIView擴展來設置角半徑,但是當我只是旋轉我的設備時它不能正常工作

import UIKit
import Foundation

extension UIView {

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

我采用了以下約束的圖像視圖 在此輸入圖像描述

當我以縱向模式運行應用程序時,輸出將是 在此輸入圖像描述

但是當我旋轉設備時它不起作用 在此輸入圖像描述

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM