小编lll*_*lll的帖子

SwiftUI - 如何在 HStack 中左、中、右对齐元素?

我正在创建一个 iOS 扫雷游戏,并希望在顶部有一个包含三条信息的栏:

  • 高分(奖杯符号旁边)[左]
  • 当前时间(计时器符号旁边)[CENTER]
  • 剩余炸弹数量(炸弹符号旁边)[右]

然而,正如您在底部的图片中看到的那样,元素并不是均匀对齐的 - 我猜垫片自动具有相同的尺寸。因此,由于屏幕左侧的文本比右侧的文本宽,因此中间的文本会向右偏移。

如何对齐这些项目,使中心时间/图像与左侧/右侧的其他对象完全位于中间?

我的代码如下所示:

struct GameView: View {
    @EnvironmentObject var game: Game
    @State var labelHeight = CGFloat.zero
    
    var body: some View {
        VStack(alignment: .center, spacing: 10) {
            Text("MINESWEEPER")
                .font(.system(size: 25, weight: .bold, design: .monospaced))
                .kerning(3)
                .foregroundColor(.red)
            
            HStack(alignment: .center, spacing: 5) {
                Image(systemName: "rosette")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .foregroundColor(.black)
                Text(game.highScoreString)
                    .font(.system(size: 15, weight: .bold, design: .monospaced))
                    .foregroundColor(.black)

                Spacer()
                
                Image(systemName: "timer")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .foregroundColor(.black)
                Text(game.timerString)
                    .font(.system(size: 15, weight: .bold, design: .monospaced))
                    .foregroundColor(.black)
                
                Spacer()
                
                Image("top_bomb")
                    .resizable() …
Run Code Online (Sandbox Code Playgroud)

user-interface xcode ios swift swiftui

45
推荐指数
2
解决办法
5万
查看次数

如何在 Swift 中使图像与其旁边的文本高度相同?

我是 Swift 的新手,正在制作一个 iOS 扫雷应用程序。在屏幕顶部,我希望在 Text() 对象旁边有一个炸弹图像,显示剩余炸弹的数量。

我想让图像和/或 HStack 调整大小到相邻文本的高度,而不必对其尺寸进行硬编码。

这可以/如何实现?

到目前为止的代码如下所示:

HStack(alignment: .center, spacing: 10) {
    Image("top_bomb")
        .resizable()
        .aspectRatio(contentMode: .fit)
    Text(String(game.bombsRemaining))
        .font(.system(size: 30, weight: .bold, design: .monospaced))
}
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1, alignment: .trailing)
Run Code Online (Sandbox Code Playgroud)

它看起来像: 扫雷应用程序

ios swift swiftui

3
推荐指数
1
解决办法
2068
查看次数

标签 统计

ios ×2

swift ×2

swiftui ×2

user-interface ×1

xcode ×1