正如PatPatchPatrick所说,您可以将堆栈视图限制为水平居中。
但是,你必须考虑如果你的字符串太长会发生什么。
您的示例字符串是:
leftStr = "Hi, there"
midStr = "HEY"
rightStr = "Hi"
并且,使用居中的堆栈视图,您会得到:
不过,假设您的字符串是:
// Set A
leftStr = "Hi, there from the Left"
midStr = "HEY MIDDLE"
rightStr = "Hi from the Right"
或:
// Set B
leftStr = "Hi, there from the Left"
midStr = "HEY"
rightStr = "Hi"
现在你得到:
2 - 哎呀...堆栈视图超出了视图的边界。
3 - 因此,我们将添加 '>=8leading and trailing (so we have a little padding on each side). Whoops, the text gets truncated... and which label(s) get...` 将取决于内容压缩优先级设置。
4 - 为避免截断,我们将标签设置为Number of Lines: 0,以便文本自动换行。也许看起来不错,也许不是。
5 - 让我们将标签的文本对齐设置为居中。也许我们想要什么?
6 - 但是,使用“Set B”字符串而不是“Set A”——可能不太好?
更好的选择可能是使用单个居中标签(带有>=8 前导和尾随约束):
并使用属性文本:
这是定义和设置属性文本的方法:
let leftStr = "Hi, there"
let midStr = "HEY"
let rightStr = "Hi"
let font1 = UIFont.systemFont(ofSize: 17.0)
let font2 = UIFont.boldSystemFont(ofSize: 26.0)
let offset = (font1.xHeight - font2.xHeight) * 0.5
let attributedStr = NSMutableAttributedString(string: leftStr + " ", attributes: [NSAttributedString.Key.font: font1])
attributedStr.append(NSAttributedString(string: midStr, attributes: [NSAttributedString.Key.font: font2, NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.baselineOffset: offset]))
attributedStr.append(NSMutableAttributedString(string: " " + rightStr, attributes: [NSAttributedString.Key.font: font1]))
theLabel.attributedText = attributedStr
作为附注,供您将来参考...
这有助于全面定义您的问题。据推测,在您的实际应用中,您不会显示:
“嗨,那里嘿嗨”
因此,完全有可能没有一种可以为您提供您想要的结果。
如果您包含真实示例来说明您的应用将显示什么以及您希望它的外观,那就更好了。