【问题标题】:How to fetch the width and height of a programatically added view in Swift/ iOS?如何在 Swift/iOS 中获取以编程方式添加的视图的宽度和高度?
【发布时间】:2021-10-16 14:26:21
【问题描述】:

我以编程方式添加了 UIView 和 UIImageView,但我需要它的宽度和高度。 是否可以获取它,如果可以,请分享如何获取它。

代码:

let View1: UIView = {
            let viewView = UIView()
            viewView.translatesAutoresizingMaskIntoConstraints = false
            viewView.contentMode = .scaleAspectFit
            print(UserDefaults.standard.bool(forKey: "backgroundColourSelected"))
            if UserDefaults.standard.bool(forKey: "backgroundColourSelected") {
                viewView.backgroundColor = self.viewColor
            }else {
                viewView.backgroundColor = .white
            }
            viewView.clipsToBounds = true
            return viewView
        }()
    
        self.canvasView.addSubview(View1)
        
        View1.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor, constant: 0).isActive = true
        View1.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor, constant: 0).isActive = true
        View1.widthAnchor.constraint(equalTo: canvasView.widthAnchor, constant: 0).isActive = true
        View1.heightAnchor.constraint(equalTo: canvasView.widthAnchor, multiplier: aspectRatio).isActive = true

【问题讨论】:

  • 使用该代码,View1 宽度将等于 canvasView 宽度,View1 高度将等于 canvasView 高度乘以 aspectRatio。所以问题是:在你的代码中你在哪里做这个?您试图在代码中的哪个位置获取宽度和高度?而且,重要的是,为什么你要获取宽度和高度?

标签: ios swift view height width


【解决方案1】:

你需要知道视图控制器的生命周期。

要获取任何视图的高度,请使用viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()

      print(view1.frame.size)
}

size 属性将打印最终高度和宽度。

【讨论】:

    【解决方案2】:

    对 ViewController 使用 override func viewWillLayoutSubviews(),对 UIView 使用 override func layoutSubviews()。

    示例:- 对于 UIViewControllers

    override func viewWillLayoutSubviews() {
        print(yourView.frame.height)
    }
    

    对于 UIViews

    override func layoutSubviews() {
        print(yourView.frame.height)
        print(yourView.frame.width)
    
    }
    

    由于您的视图位于函数内部,因此只需将其移出

    class YourController / YourView {
    private let imgView: UIImageView = {
        let iv = UIImageView()
        // do whatever you want with your image using iv. eg. iv.contentMode = .scaleAspectFit or iv.image = UIImage(named: "custom_img")
        return iv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(imgView)
        //set constraints for your
    }
    
    // then use layoutSubViews(for views) / viewWillLayoutSubViews (for controller) and calculate the height
    

    }

    【讨论】:

    • 我尝试使用上述提供的解决方案,但没有奏效。我在返回此视图的函数中添加了一个 UIView。以编程方式为此视图添加了约束。你能帮我在我的代码中的正确位置添加上面的代码吗?我在我的问题中添加了上面的代码。我需要得到视图的最终宽度和高度。 @Rishabh Shukla
    • 只是把那个视图放在那个函数之外。
    • 我已经编辑了我的答案,检查它是否适合你。
    猜你喜欢
    • 2018-12-16
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2023-03-20
    • 2013-12-14
    相关资源
    最近更新 更多