如何在两个标签之间调整UIDatePicker的大小

时间:2018-03-02 19:07:46

标签: ios swift uidatepicker

我正在尝试让UIDatePicker在多个设备上兼容。我有标签和一切正常,我只想根据设备调整DatePicker的高度。让它“挤压”#39;标签之间是目标。我该怎么做?

编辑:更准确的问题: 如何让两个标签保持UIDatePicker保持15像素并调整大小以便执行此操作?我希望UIDatePicker在设备更改时垂直拉伸/压缩。谢谢!

1 个答案:

答案 0 :(得分:0)

UIStackView是完成此操作的完美方式。据我所知,您希望看到垂直的顶部和底部UILabel以及它们之间UIPickerView

编程方式:

import UIKit

final class ViewController: UIViewController {

    lazy var verticalStackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.addArrangedSubview(leftLabel)
        stack.addArrangedSubview(middlePicker)
        stack.addArrangedSubview(rightsLabel)
        return stack
    }()

    let leftLabel: UILabel = {
        let label = UILabel()
        label.text = "Maybe something?"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let rightsLabel: UILabel = {
        let label = UILabel()
        label.text = "Maybe something?"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()


    let middlePicker: UIPickerView = {
        let picker = UIPickerView()
        // Some settings
        return picker
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(verticalStackView)

        // Auto layout
        verticalStackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        verticalStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        verticalStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        verticalStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

        // U can manipulate height of both labels, picker view going to be squished by those labels, setting more height of both of them going to make him smaller

        leftLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true // 50 height ?
        rightsLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true // 50 height ?
    }

}

随意提出任何问题。