【问题标题】:How to center text inside a round button using swiftUI?如何使用 swiftUI 在圆形按钮内居中文本?
【发布时间】:2020-03-06 23:24:28
【问题描述】:

我正在 SwiftUI 中开发一个代表硬币的视图。硬币是一个按钮。

在硬币内部,我想将代表金额的文本居中,如果文本是“0.01”代表 1 美分。

问题是,如果文本大小为 30,我无法在按钮内居中显示文本。这是我的尝试,将填充设置为.all

Button(action: addToTotal)
    {
        Text(coinAmount.toTwoDecimalOrTruncatedString())
            .font(.system(size: 30))
            .fontWeight(.bold)
            .multilineTextAlignment(.center)
            .lineLimit(0)

    }
    .padding(.all)
    .accentColor(.white)
    .frame(width: 100, height: 100, alignment: .bottom)
    .background(Color.orange)
    .cornerRadius(100)

cointAmountFloat

toTwoDecimalOrTruncatedString 是一种扩展方法,如果数字是浮点数,则将硬币金额截断为两位小数的字符串。

我认为问题是由于填充造成的,但我无法在按钮视图中将文本像素完美居中:

有什么建议吗?

【问题讨论】:

    标签: ios swiftui


    【解决方案1】:

    只需在.frame 中使用居中对齐,即

    }
    .padding(.all)
    .accentColor(.white)
    .frame(width: 100, height: 100, alignment: .center) // << here!
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 2018-01-17
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多