SwiftUI 将 Label 的垂直对齐方式更改为居中图像和文本

Posted

技术标签:

【中文标题】SwiftUI 将 Label 的垂直对齐方式更改为居中图像和文本【英文标题】:SwiftUI change vertical alignment of Label to center image and text 【发布时间】:2021-10-23 09:15:47 【问题描述】:

我试图将 SwiftUI 标签的图像和文本垂直居中。我试图覆盖图像的对齐指南,但它没有用。有什么想法吗?

        Label 
            Text("Test fdasf \n adfsa dsfsd f asdf \n asd fasd fads sad fda")
         icon: 
            Image(systemName: true ? "checkmark.circle.fill" : "circle")
                .alignmentGuide(VerticalAlignment.top) 
                    $0[VerticalAlignment.center]
                
        

【问题讨论】:

【参考方案1】:

我们可以使用自定义标签样式来做到这一点,比如

struct DemoStyle: LabelStyle 
    func makeBody(configuration: Configuration) -> some View 
        HStack(alignment: .center)     // << here !!
            configuration.icon
            configuration.title
        
    

并使用它

Label 
    Text("Test fdasf \n adfsa dsfsd f asdf \n asd fasd fads sad fda")
 icon: 
    Image(systemName: true ? "checkmark.circle.fill" : "circle")

.labelStyle(DemoStyle())

使用 Xcode 13 / ios 15 测试

【讨论】:

谢谢!有什么方法可以使用 layoutGuides 解决它?

以上是关于SwiftUI 将 Label 的垂直对齐方式更改为居中图像和文本的主要内容,如果未能解决你的问题,请参考以下文章