在SwiftUI中,我该如何使一个SF符号水平居中对齐?

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

How can I make an SF symbol horizontally align centered in SwiftUI?

问题

我有一个 SwiftUI 图像视图,只显示一个 SF 符号:

```swift
GeometryReader { g in
    Image(systemName: "a.square")
        .font(.system(size: g.size.width))
}

它呈现如下:

在SwiftUI中,我该如何使一个SF符号水平居中对齐?

我尝试使用 .multilineTextAlignment(.center) 修改器来将其居中,但没有任何效果。


<details>
<summary>英文:</summary>

I have a SwiftUI Image view that displays only an SF symbol:

GeometryReader { g in
Image(systemName: "a.square")
.font(.system(size: g.size.width))
}
}


It renders like this:

[![Preview of Image view](https://i.stack.imgur.com/aVSKZl.png)](https://i.stack.imgur.com/aVSKZ.png)


I tried modifying the view with the `.multilineTextAlignment(.center)` modifier to center it, and that didn&#39;t do anything.

</details>


# 答案1
**得分**: 2

```plaintext
你可以尝试添加以下命令行:

    .position(x: g.size.width / 2, y: g.size.width / 2)

你写的代码看起来像这样:

    GeometryReader { g in
       Image(systemName: "a.square")
           .font(.system(size: g.size.width))
           .position(x: g.size.width / 2, y: g.size.width / 2)
    }
}
英文:

You can try adding this command line for it:

.position(x: g.size.width / 2, y: g.size.width / 2)

The code you wrote looks like this:

GeometryReader { g in
   Image(systemName: &quot;a.square&quot;)
       .font(.system(size: g.size.width))
       .position(x: g.size.width / 2, y: g.size.width / 2)
}

}

在SwiftUI中,我该如何使一个SF符号水平居中对齐?

答案2

得分: 0

为什么不用声明式的方式?

    VStack {
        Image(systemName: "a.square")
            .resizable()
            .aspectRatio(1.0, contentMode: .fit)
            .padding()
        Spacer()
    }
英文:

Why not the declarative way?

VStack {
    Image(systemName: &quot;a.square&quot;)
        .resizable()
        .aspectRatio(1.0, contentMode: .fit)
        .padding()
    Spacer()
}

huangapple
  • 本文由 发表于 2023年2月19日 08:37:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497296.html
匿名

发表评论

匿名网友

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

确定