更改UIView的变换不会影响约束

时间:2018-02-12 13:29:59

标签: ios swift autolayout ios11

在iOS 11中,更改UIView的转换属性(例如缩放)不会影响绑定到此视图的约束。在iOS 10中,所有工作都按预期工作。

我的代码:

import UIKit

class TestViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // top view
        let topView = UIView()
        topView.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
        topView.backgroundColor = .black
        view.addSubview(topView)

        topView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)

        // bottom view
        let bottomView = UIView()
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        bottomView.backgroundColor = .black
        view.addSubview(bottomView)

        NSLayoutConstraint.activate([
            bottomView.heightAnchor.constraint(equalToConstant: 200),
            bottomView.widthAnchor.constraint(equalToConstant: 200),
            bottomView.leftAnchor.constraint(equalTo: topView.leftAnchor),
            bottomView.topAnchor.constraint(equalTo: topView.bottomAnchor, constant: 8)
        ])
    }
}

期待什么(iOS 10):

expected result

有什么(iOS 11):

enter image description here

如您所见,topView已缩放,但bottomView未正确布局。我该如何解决?

2 个答案:

答案 0 :(得分:2)

来自Apple的UIView / Transform文档(https://developer.apple.com/documentation/uikit/uiview/1622459-transform):

  

警告

     

当此属性的值不是identity变换时,frame属性中的值是未定义的   应该被忽略。

所以,你在iOS 10 中得到的结果恰好是你得到的,而不是正确的结果。

答案 1 :(得分:-1)

底部视图发生的事情是,在您告诉它缩放到%50并且它添加8个像素之前,它正在与顶视图的左锚点对齐。我会硬编码左边的约束。查看This Tutorial以获取有关如何使用可视格式语言执行此操作的指南。

相关问题