使用Autolayout将UILabel沿其父视图底部对齐

时间:2014-09-09 05:33:36

标签: ios swift uilabel autolayout

我试图在其父视图的底部显示一个UILabel,其前导和尾部设置为伸展到父视图的边界。不幸的是,标签根本没有出现在屏幕上。我已验证父视图是否正确填充整个屏幕。

    //set up parent view
    let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)
    let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
    vibrancyEffectView.frame = blurEffectView.bounds
    vibrancyEffectView.autoresizingMask = .FlexibleWidth | .FlexibleHeight

    //Label for vibrant text
    let vibrantLabel = UILabel()
    vibrantLabel.text = "My Label"
    vibrantLabel.textColor = UIColor(white: 0.64, alpha: 1)
    vibrantLabel.textAlignment = .Center
    vibrantLabel.sizeToFit()
    vibrantLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
    vibrancyEffectView.contentView.addSubview(vibrantLabel)

    vibrancyEffectView.addConstraint(NSLayoutConstraint(item: vibrantLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: vibrancyEffectView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 15))
    vibrancyEffectView.addConstraint(NSLayoutConstraint(item: vibrantLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: vibrancyEffectView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
    vibrancyEffectView.addConstraint(NSLayoutConstraint(item: vibrantLabel, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: vibrancyEffectView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
    vibrancyEffectView.addConstraint(NSLayoutConstraint(item: vibrantLabel, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: vibrantLabel, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 30))

    blurEffectView.contentView.addSubview(vibrancyEffectView)

这可能是由于父级上设置的自动调整大小,还是我的自动布局限制不正确?另外我想知道处理高度的最佳方法是什么 - 我想确保文本适合它。

2 个答案:

答案 0 :(得分:2)

我认为你的一些限制是错误的。

您将标签的底部固定在活力视图的底部,常数为15 - 这将在底部下方 15点。

您还要将标签的高度固定在自己的高度加上30 - 这是不可理解的,我很惊讶您没有看到错误日志。标签不需要高度限制,因为它将具有基于文本值的内在内容大小 - 您也不需要sizeToFit调用。要使标签流到多行,请将numberOfLines属性设置为零。

答案 1 :(得分:-1)

要为标签添加的约束类型。

左,上,宽度和高度

TOP约束(样本):

mylabel.setTranslatesAutoresizingMaskIntoConstraints(false) 

self.addConstraint(NSLayoutConstraint(

                item:mylabel, attribute:NSLayoutAttribute.Top,

                relatedBy:NSLayoutRelation.Equal, toItem:myView,

                attribute:NSLayoutAttribute.Bottom, multiplier:1.0, constant: 0.0))