如何在SwiftUI中动态找出字符串的宽度

如何在SwiftUI中动态找出字符串的宽度

本文介绍了如何在SwiftUI中动态找出字符串的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个文本叫做: This .我想弄清楚称为 This 的文本的宽度,以便可以为另一个视图的框架分配宽度.我该怎么办?

Let's say I have a text called: This. I want to figure out the width of the text called This so that I can assign a width to another view's frame. How do I go about it?

struct BadgeTextView: View {

var text: String

var body: some View {
    Rectangle()
        .fill(Color.red)
    .cornerRadius(3)
        .frame(width: text.???, height: <#T##CGFloat?#>, alignment: <#T##Alignment#>)

}
}

推荐答案

String 的扩展应基于Sweeper的建议,以使您获得 String 的宽度提供了某种字体:

This extension to String should build on Sweeper's suggestion to let you get the width of a String given a certain font:

extension String {
   func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width
    }
}

它的用法如下: let width ="SomeString" .widthOfString(usingFont:UIFont.systemFont(ofSize:17,weight:.bold))

这篇关于如何在SwiftUI中动态找出字符串的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:09