内容拥抱和内容压缩阻力,视图之间的边距最小

问题描述 投票:0回答:1

我试图创建一个 UI,其中两个标签水平放置,与屏幕上的其他边缘平行,以便它们可以根据接收到的内容而增长。

我尝试设置内容拥抱和压缩阻力优先级,并且能够让标签根据内容增长,但是当任何一个标签收到更多内容时,它们开始相互重叠。

如何设置约束?以这种方式,标签可以根据它们收到的内容进行增长,如果内容更大,那么它们应该开始截断自己,因此之间应该始终有一个最小的边距,这样它们就不会开始相互重叠,并且如果内容两个标签都有足够的错误,那么它们应该平均分配空间。

ios autolayout storyboard constraints uilabel
1个回答
0
投票

仅使用故事板中的约束设置,无法根据标签的组合宽度自动按比例调整两个标签的宽度。您需要一些代码才能完成这项工作。

我创建了一个简单的 iOS 应用程序。从一个新的 iOS 应用程序项目开始。将两个标签添加到视图控制器的安全区域。在故事板中,添加以下约束:

  • 设置左标签的前导约束
  • 设置右侧标签的尾随约束
  • 设置两个标签的垂直位置(假设相同)
  • 将左标签的尾随设置为 <= the right label's leading with a constant, of say 10, to provide a small gap between them.
  • 将左侧标签的宽度约束设置为某个常量(这将在代码中进行调整,因此故事板中的值并不重要)。

这些就位后,您将在故事板中看到类似以下内容:

在我自己的测试中,我还设置了以下标签属性:

  • 左标签左对齐
  • 左标签到“截断尾部”的换行符
  • 右标签右对齐
  • “截断头”换行符的右侧标签

使用以下代码更新 ViewController.swift:

import UIKit

class ViewController: UIViewController {
    @IBOutlet var left: UILabel!
    @IBOutlet var right: UILabel!
    @IBOutlet var leftWidthC: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Test with two short strings
        //left.text = "Hello there"
        //right.text = "Goodbye"

        // Test with one long and one short string
        //left.text = "This is a really long string to see how it works"
        //right.text = "A short one"

        // Test with one short and one long string
        //left.text = "A short one"
        //right.text = "This is a really long string to see how it works"

        // Test with two long strings
        left.text = "Hello there XXX XXX XXX XXX XXX"
        right.text = "YYY YYY YYY YYY Goodbye Bob"
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // Get the width between the two ends of the two labels
        let vwidth = right.frame.maxX - left.frame.minX
        // Get the full width of the left label
        left.sizeToFit()
        let lwidth = left.frame.width
        // Get the full width of the right label
        right.sizeToFit()
        let rwidth = right.frame.width
        // Calculate the percentage of the left label width versus the combined label width
        let lp = lwidth / (lwidth + rwidth)
        // Calculate the final displayed width of the left label
        let plw = lp * vwidth
        // Update the left label's width constraint
        leftWidthC.constant = min(lwidth, plw)
        // The right label's width will automatically adjust due to other constraints
    }
}

现在将两个标签连接到其插座。最后,将左侧标签的宽度约束连接到其出口。

您现在可以使用不同的标签值运行和测试代码以检查结果。

© www.soinside.com 2019 - 2024. All rights reserved.