[英]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.