具有动态宽度的XIB,将高度固定在中心 - 编程约束似乎不起作用

时间:2017-06-06 13:43:40

标签: ios swift xcode xib

我使用自由格式创建了一个.xib并像这样实现它

if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView {

        view.addSubview(alertView)

        alertView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)

        view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 20))
        view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20))

        alertView.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin]
        self.view.layoutIfNeeded()

  }

我在viewDidAppear中调用此代码。中心似乎有效,但似乎trailingleading没有任何影响。我希望它们的距离为20,我的alertView应该有一个固定的高度并显示在中心。

xib的大小始终相同(见截图)

我最初的目标是获得一个xib,我可以在每个设备的每个视图中实现。那么获得这个的最佳方法是什么?

xib file 我的xib文件 iphone 7 模拟器iphone 7 iphone 4 模拟器iphone 4

1 个答案:

答案 0 :(得分:1)

您正在混合自动布局和固定放置(使用自动调整遮罩)。您要做的是完全使用自动布局,以便视图自动调整其布局。你说你想要一个20的水平距离,一个固定的高度并且居中,所以我会这样做:

if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView {

    view.addSubview(alertView)

    // Start using auto layout
    alertView.translatesAutoresizingMaskIntoConstraints = false

    // Set the leading and trailing constraints for horizontal placement
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: -20))
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20))

    // Centre it vertically
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))

    // Set the fixed height constraint
    let fixedHeight: CGFloat = 100
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 0, constant: fixedHeight))
}

无论设备,超视图,方向等如何变化,这都能满足您的需求。