设置 UIView 大小以适应子视图

Set UIView size to fit subViews(设置 UIView 大小以适应子视图)
本文介绍了设置 UIView 大小以适应子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIView,其中包含两个具有动态高度的 UILabel.我希望 UIView 适合 UILabel 的大小 + 一些填充.现在我正在绘制标签,然后将 UIView 的宽度和高度约束设置为标签的组合大小.

I'm having a UIView that's containing two UILabels, which have dynamic heights. I want the UIView to fit the size of the UILabels + some padding. Right now I'm drawing the labels and then sets the UIView's width and height constraints to the combined size of the labels.

现在我正在这样做:

func populateWithMessage(headline: String?, message: String) {
    // Sets text
    self.headerLabel.text = headline
    self.messageLabel.text = message

    self.headerLabel.sizeToFit()
    self.messageLabel.sizeToFit()

    self.layoutSubviews()

    // Finding the label with the greatest width
    var longestLabel: UILabel!
    if self.headerLabel.frame.width > self.messageLabel.frame.width {
       longestLabel = self.headerLabel
   } else {
       longestLabel = self.messageLabel
   }
   
   let combinedLabelHeight = self.headerLabel.frame.height + self.messageLabel.frame.height
   
   // Update the container view's constraints
   self.containerViewWidtConstraint.constant = longestLabel.frame.width + 10
   self.containerViewHeightConstraint.constant = combinedLabelHeight + 10

   self.updateConstraints()
}

不幸的是,它不起作用.我正在使用 Swift 2.3 和 Autolayout.

Unfortunately it doesn't work. I'm using Swift 2.3 and Autolayout.

推荐答案

您可以使用情节提要本身来完成.

You can do it using the storyboard itself.

将视图的底部约束设置为第二个 UIlabel.所以当label的高度增加时,UIView的高度也会增加.

Set the View's bottom constraint to second UIlabel. So when the height of label increases, UIView's height will also increases.

这篇关于设置 UIView 大小以适应子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)