不要在SwiftUI中将文本字体更改为粗体时调整堆栈内容的大小。

huangapple go评论71阅读模式
英文:

Don't resize stack content when changing text font to bold in SwiftUI

问题

我有一个包含两个文本的水平堆栈:

HStack {
    Text("文本1")
    Text("文本2")
}

在某个时刻,当我将第一个文本的字体改为粗体时,它显然会重新调整大小,并将第二个文本推到右边。

我想避免这种情况。标签肯定可以放在第二行,框架可以垂直调整大小,但我希望在水平方向上保持静态。

不确定最佳方法是什么?

提前感谢。

英文:

I have an horizontal stack with two Text :

HStack {
    Text("text1")
    Text("text2")
}

At some point, when I change the first text font to a bold one, it obviously resizes it and pushes the second text on the right.

I would like to avoid this. The label could go on a second line for sure, the frame could resize vertically but I want to keep it static horizontally.

Not sure what is the best way to do this ?

Thanks in advance

答案1

得分: 1

使用固定宽度:

Group {
    if bold {
        Text("text1").bold()
    } else {
        Text("text1")
    }
}.frame(width: 50)

如果水平空间不足,文本将换行到下一行。

或者,将“较小”的文本(非粗体文本)作为“较大”的文本的覆盖层。然后使较大的文本不可见。

if bold {
    Text("text1").bold()
} else {
    // 不可见的粗体文本...
    Text("text1").bold().opacity(0)
        .overlay {
            // ...将非粗体文本作为覆盖层
            Text("text1")
        }
}

这也可以写成:

Text("text1").bold().opacity(bold ? 1 : 0)
    .overlay {
        if !bold {
            Text("text1")
        }
    }
英文:

Use a fixed width:

Group {
    if bold {
        Text("text1").bold()
    } else {
        Text("text1")
    }
}.frame(width: 50)

If there is not enough horizontal space, the text will just wrap to the next line.

Alternatively, put the "smaller" text (the non-bold one) as an overlay of the "bigger" text. Then make the bigger text invisible.

if bold {
    Text("text1").bold()
} else {
    // invisible bold text...
    Text("text1").bold().opacity(0)
        .overlay {
            // ...with the non-bold text as an overlay
            Text("text1")
        }
}

This can be also written as:

Text("text1").bold().opacity(bold ? 1 : 0)
    .overlay {
        if !bold {
            Text("text1")
        }
    }

huangapple
  • 本文由 发表于 2023年7月31日 20:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定