【问题标题】:Dynamic corner Radius for landscape and portrait横向和纵向的动态角半径
【发布时间】:2018-08-02 11:27:09
【问题描述】:

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

import UIKit
import Foundation

extension UIView {

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

我使用以下约束拍摄图像视图

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

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

【问题讨论】:

  • 请查看我的answer,如果有用请您接受。以便将来对其他人有所帮助。

标签: ios swift uiview cornerradius


【解决方案1】:

layoutSubviews方法中设置圆角半径。

如果您需要圆形视图,请将角半径设置为宽度/高度的一半。

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

【讨论】:

    【解决方案2】:

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

    enter image description here

    还通过乘数为 superview 提供相等的宽度或高度,这样当你旋转 UIView 的尺寸时,你就会得到这个结果。

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

    【讨论】:

      【解决方案3】:

      旋转时,您的视图大小正在发生变化,并且之前应用的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。

      【讨论】:

        【解决方案4】:

        您也可以通过编程方式检查设备是水平的还是垂直的,然后像 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
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-29
          • 2015-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多