【问题标题】:Shadow layer not resizing when UIView frame changedUIView 框架更改时阴影层未调整大小
【发布时间】:2018-10-09 01:59:00
【问题描述】:

Issue Image ScreenShot

class ViewController: UIViewController {
    var shadow : UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        shadow = UIView(frame: CGRect(x: 50,y: 50,width: 150,height:150))
        shadow.backgroundColor = .red
        shadow.dropShadow()
        self.view.addSubview(shadow)

    }

    @IBAction func btnActn(_ sender: Any) {self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)

    }

}

extension UIView {
 func dropShadow(scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: 1, height: 1)
        layer.shadowRadius = 2
        layer.shadowPath = UIBezierPath(rect: bounds).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }

}

UIView框架改变时阴影层不调整大小,如何改变等于框架大小,这是我的UIviewcontroller的全部代码

【问题讨论】:

    标签: ios swift uiview shadow


    【解决方案1】:

    您有很多方法可以做到这一点:

    首先:在“viewWillLayoutSubviews”方法中,你必须像这样调用你的影子方法。因此,每当您更改框架时,您就不必担心图层。每当您更改视图时,此方法都会自动调用:-

    override func viewWillLayoutSubviews() {
        shadow.dropShadow()
    }
    

    第二:当您要重新构图时,您必须为“autoresizesSubviews”设置“true”,如下所示:

    @IBAction func btnActn(_ sender: Any) {
            self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
            self.shadow.autoresizesSubviews = true
        }
    

    【讨论】:

    • 这不应该在viewDidLayoutSubviews里做吗?如果你在 viewWillLayoutSubviews 中做,新的框架还没有计算出来。
    【解决方案2】:
    Before calling dropShadow, first, try to call layoutIfNeeded
    
            @IBAction func btnActn(_ sender: Any) {
              self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
              self.shadow.layoutIfNeeded()
              self.shadow.dropShadow()
            }
    

    【讨论】:

      【解决方案3】:

      问题是当视图控制器加载到内存时,您只在viewDidLoad() 中绘制一次阴影。每次重绘链接到的视图时都需要调用dropShadow

      你可以在更改shadow的框架后调用dropShadow来实现。

      @IBAction func btnActn(_ sender: Any) {
          self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
          self.shadow.dropShadow()
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-18
        • 2017-07-31
        相关资源
        最近更新 更多