繁体   English   中英

使用自动布局将UILabel沿其父视图的底部对齐

[英]Align UILabel along bottom of its parent view using 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)

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

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

你寄托在标签底部的活力视图的底部,用15恒定的-这将针它的底部低于 15分。

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

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

左,上,宽和高

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM