UISlider布局忽略宽度

时间:2016-07-21 12:01:54

标签: swift uikit uislider nslayoutconstraint

我需要添加一个包含UILabelUISlider的弹出式视图,但我无法设置UISlider的宽度。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        frontPanel = UIView()
        frontPanel!.backgroundColor = UIColor.whiteColor()
        frontPanel!.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(frontPanel!)

        valueSlider = UISlider()
        valueSlider!.translatesAutoresizingMaskIntoConstraints = false
        valueSlider!.frame = CGRect(x: 0,
                                    y: 0,
                                    width: frontPanel!.frame.width - 16,
                                    height: 35)

        sliderLabel = UILabel()
        sliderLabel!.translatesAutoresizingMaskIntoConstraints = false

        sliderLabel!.text = "Adjust value"

        let frontPanelSubviews: [String : AnyObject] = [
            "label" : sliderLabel!,
            "slider" : valueSlider!
        ]

        frontPanel!.addSubview(sliderLabel!)
        frontPanel!.addSubview(valueSlider!)

        frontPanel?.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]-[slider]-|",
            options: [],
            metrics: nil,
            views: frontPanelSubviews)
        )
        frontPanel?.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|",
            options: [],
            metrics: nil,
            views: frontPanelSubviews)
        )
        frontPanel?.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat("H:|-[slider]-|",
            options: [],
            metrics: nil,
            views: frontPanelSubviews)
        )

    }

    override func viewDidLayoutSubviews() {
        frontPanel?.frame = CGRect(x: 0,
                                   y: view.frame.height - 75,
                                   width: view.frame.width,
                                   height: 75)
    }

    @IBOutlet weak var backPanel: UIView!
    @IBOutlet weak var valueLabel: UILabel!

    var frontPanel: UIView?
    var valueSlider: UISlider?
    var sliderLabel: UILabel?
}

在此示例中,UISlider的宽度始终与UILabel相同。

如果我只使用H:|-[label]-[slider]-|之类的水平布局约束,UISlider获取width == 0

如何让UISlider使用父视图的整个宽度(减去每边8个点的空间)?

1 个答案:

答案 0 :(得分:1)

frontPanel!.translatesAutoresizingMaskIntoConstraints = true

frontPanelsubview的{​​{1}},您设置的是ViewController.view。我的理解如下。