减少父级UIview的约束时,如何使迅速的UIview子元素自动缩小?

时间:2018-10-24 11:52:40

标签: ios swift

class ViewController{                

    @IBOutlet weak var UiCalendarView: UIView!
    @IBOutlet weak var UiCalendarViewConstraint: NSLayoutConstraint!
    let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: 373, height:300))


    override func viewDidLoad() {
        super.viewDidLoad()
        UiCalendarView.addSubview(self.calendar)
        UiCalendarViewConstraint.constant = 23
    }
}

但是UiCalendarViewConstraint.constant所做的更改并不多,因为子组件calendar具有自己的高度,并且保持不变。

1 个答案:

答案 0 :(得分:0)

您需要向子项添加约束并在父项的大小更改时捕获参考,以根据height更改子项的约束。 但是,如果您将孩子的父母固定在顶部和底部,则当父母的尺寸更改时,它会自动更改

let parentView = UIView()
let childView = UIView()
parentView.addSubView(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
parentView.translatesAutoresizingMaskIntoConstraints = false

childView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
childView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
childView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
childView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true

当您自动更改父级的高度或宽度时,此代码段将使子级填充父级View,并对其进行调整。