簡體   English   中英

SwiftUI 按鈕編譯器錯誤還是我的?

[英]SwiftUI Button compiler bug or mine?

我有以下代碼:

import SwiftUI

enum OptionButtonRole {
    case normal
    case destructive
    case cancel
}

struct OptionButton {
    var title: String
    var role: OptionButtonRole
    let id = UUID()
    var action: () -> Void
}

struct OptionSheet: ViewModifier {
    @State var isPresented = true
    var title: String
    var buttons: [OptionButton]
    
    init(title: String, buttons: OptionButton...) {
        self.title = title
        self.buttons = buttons
    }
    
    func body(content: Content) -> some View {
        content
            .confirmationDialog(title, 
                                isPresented: $isPresented, 
                                titleVisibility: .visible) {
                ForEach(buttons, id: \.title) { button in
                    let role: ButtonRole? = button.role == .normal ? nil : button.role == .destructive ? .destructive : .cancel
                    Button(button.title, role: role, action: button.action)
                }
            }
    }
}

它構建並且我的應用程序顯示帶有指定按鈕的選項表。

但是,如果我使用替代Button.init ,即如果我用以下代碼替換正文:

func body(content: Content) -> some View {
    content
        .confirmationDialog(title, 
                            isPresented: $isPresented, 
                            titleVisibility: .visible) {
            ForEach(buttons, id: \.title) { button in
                let role: ButtonRole? = button.role == .normal ? nil : button.role == .destructive ? .destructive : .cancel
                Button(role: role, action: button.action) {
                    Text(button.title)
                }
            }
        }
}

然后,Xcode 掛起並執行以下活動:

在此處輸入圖像描述

我的代碼中有錯誤還是編譯器錯誤(Xcode 版本 14.1 (14B47b))?

雖然您的代碼在技術上是正確的,但視圖邏輯評估變量值的能力可能會占用大量編譯器,尤其是當ForEach中有多個鏈接的三元組和邏輯時(這似乎比人們想象的要大)。

我很想將條件邏輯完全移到循環之外,這樣您就可以調用一個方法,而不需要評估和存儲局部變量。 您可以在您的視圖中將其設為私有func ,或作為自定義枚舉的擴展。 例如:

extension OptionButtonRole {
  var buttonRole: ButtonRole? {
    switch self {
      case .destructive: return .destructive
      case .cancel: return .cancel
      default: return nil
    }
  }
}

// in your view

ForEach(buttons, id: \.title) { button in
  Button(role: button.role.buttonRole, action: button.action) {
    Text(button.title)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM