【问题标题】:Adjust UILabel on the content size with autolayout in iOS在 iOS 中使用自动布局调整 UILabel 的内容大小
【发布时间】:2018-08-12 16:46:15
【问题描述】:

我正在尝试使用内在内容大小来了解动态布局的基础知识。如图所示,我有两个水平的 UILabel,这将是我的默认布局。如何使布局约束使

  • 如果两个标签中的任何一个的内容大小大于另一个,则应垂直堆叠排列
  • 另外,如果两个标签内容大小中的任何一个大于一行,我们如何使文本增长满足垂直排列

【问题讨论】:

  • "如果两个标签中的任何一个的内容大小大于另一个,则应垂直堆叠排列"。在第一种情况下(图像),第二个标签内容大小明显大于第一个标签,但您希望它们水平。你能澄清一下吗?
  • @PuneetSharma 考虑带有两个标签“自动布局测试”和“自动布局很有趣,我疯了!!!:)”的第二部分。默认情况下,uilabels 水平排列由于第二个标签文本的字符比第一个标签多,因此第二个标签应该是第一个标签
  • 这意味着两个标签应该水平堆叠,直到它们大于固定宽度。
  • @PuneetSharma 是的,没错

标签: ios autolayout uilabel


【解决方案1】:

你可以给stackView添加两个标签,如果intrinsicContentSize之和用UIScreen.main.bounds.width减去stackView的左右边距检查。

if (label1.intrinsicContentSize.width + label2.intrinsicContentSize.width) > (UIScreen.main.bounds.width - 48/* 48 is the left and right margins*/) {
     stackView.axis = .vertical
}else {
     stackView.axis = .horizontal
}

记得将标签的 numberOfLines 设置为 0。

【讨论】:

  • 谢谢。我已经使用约束添加了我的答案
  • @Nassif Great Happy Coding
【解决方案2】:

我能够使用四个约束出口来达到这个条件。

  • 将 L1 和 L2 视为分别水平放置的 firstLabel 和 secondLabel
  • 将 L1 的前导空格添加到超级视图
  • 将 L1 的顶部空间添加到超级视图
  • 为 L1 添加高度 >= someValue
  • 为值 >= someValue 且优先级为 999 的 L1 添加尾随空格
  • 将 L2 的前导空格添加到 L1 的前导,给予低优先级并进行 nsconstraint 出口连接
  • 从 L2 到 L1 添加水平空间,给予低优先级并建立 nsconstraint 出口连接
  • 添加从 L2 到 L1 的 align top ,给予低优先级并建立 nsconstraint 出口连接
  • 从 L2 到 L1 添加垂直空间,给予低优先级并进行 nsconstraint 出口连接
  • 为 L2 添加高度 >= someValue
  • 为值 >= someValue 且优先级为 999 的 L2 添加尾随空格

        let firstWidth : CGFloat = (firstLabel?.intrinsicContentSize.width)!
    let secondWidth : CGFloat = (secondLabel?.intrinsicContentSize.width)!
    
    if (firstWidth + secondWidth) <= self.view.frame.size.width - 45.0 {
    
         secondLabelLeadingConstraintTofirstLabelLeading?.priority = UILayoutPriority(rawValue: 250)
         secondLabelSpacingConstraintTofirstLabel?.priority = UILayoutPriority(rawValue: 1000)
         secondLabelTopConstraintTofirstLabelTop?.priority = UILayoutPriority(rawValue: 1000)
         secondLabelTopConstraintTofirstLabelBottom?.priority = UILayoutPriority(rawValue: 250)
    
    }
    else {
    
        secondLabelLeadingConstraintTofirstLabelLeading?.priority = UILayoutPriority(rawValue: 1000)
        secondLabelSpacingConstraintTofirstLabel?.priority = UILayoutPriority(rawValue: 250)
        secondLabelTopConstraintTofirstLabelTop?.priority = UILayoutPriority(rawValue: 250)
        secondLabelTopConstraintTofirstLabelBottom?.priority = UILayoutPriority(rawValue: 1000)
    
    }
    

【讨论】:

    猜你喜欢
    • 2014-08-19
    • 2013-06-14
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多