【问题标题】:Swift: conditional modifier for .font of text()Swift:文本()的.font的条件修饰符
【发布时间】:2020-02-22 12:29:18
【问题描述】:

我是 Swift 的新手,还在学习中。我试图根据布尔变量格式化文本。它适用于字体大小和样式。但它不适用于 .bold() 或 .italic 等样式。知道怎么做吗?我也试过 ViewModifier,但也有同样的问题。

struct ContentView: View {
    @State private var txtFont = false

    var body: some View {
        VStack{
            Spacer()
            Button("Toggle the Textproperty") {
                self.txtFont.toggle()
            }
            Spacer()
            Text("Hello, World!")
                .font(txtFont ? .largeTitle : .none)
                .bold()
                .italic()
//                txtFont ? .bold() : .none <= this line won't work
            Spacer()
        }
    }
}

基于布尔决策将选择器的样式从 DefaultPickerStyle 更改为 SegmentedPickerStyle 时,我遇到了同样的问题。我需要这个来让用户界面更加用户友好。

任何想法如何实现这一点?

【问题讨论】:

    标签: swift properties modifier


    【解决方案1】:

    你应该选择.fontWeight(_ weight: Font.Weight?)

    Text("Hello, World!")
           .fontWeight(txtFont ? .bold : .regular)
    

    如果你想一次设置多个字体属性,也很简单,

    Text("Hello, World!")
                .font(txtFont ? .largeTitle.bold().italic() : .none)
    

    【讨论】:

    • 谢谢。这行得通。我尝试使用.font(...) 没有结果。但是.italic() 就不行了,对吧?
    • 非常感谢。这有助于我更好地理解它是如何工作的。
    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 2021-11-18
    • 2021-12-17
    • 2022-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    相关资源
    最近更新 更多