【问题标题】:What do we have as UIButton(Sender: UIButton) in swiftui? [closed]我们在swiftui中作为 UIButton(Sender: UIButton) 有什么? [关闭]
【发布时间】:2021-06-04 06:02:52
【问题描述】:

在 UIKit 中,我通过代码捕获按钮发送者(点击了哪个按钮)

       let colorVC = UIColorPickerViewController()
       colorVC.delegate = self
       clickedButton = sender
       present(colorVC, animated: true)
   }

我想在 SwiftUI 中完成同样的事情。

flagList.name 来自 struct,我想知道点击了哪个按钮,以便相应地调整 Flag 名称。

``` Button(action: {
            
            print("tapped")
        }, label: {
            List(flagList) { flagList in
             
                
                
                HStack(spacing: 15){
                Image(flagList.flagName)
                    .resizable()
                    .scaledToFit()
                    .clipShape(Circle())
                    .frame(width: 30, height: 30, alignment: .trailing)
                    
               
                    
                Text(flagList.name)
                    
                    .font(.system(size: 25, weight: .light, design: .default))

                }
            }


【问题讨论】:

    标签: ios swift uikit swiftui-form


    【解决方案1】:

    首先,我认为您的按钮放错了位置。您可能需要一个按钮列表,而不是由列表组成的按钮。

    然后,您可以存储一个表示当前选定按钮的属性:

    @State var currentSelectedFlagName: String
    

    请注意,我说的是代表,而不是商店。在 SwiftUI 中,您不应存储对单个视图(包括按钮)的引用。

    然后,您可以在点击时将currentSelectedFlagName 设置为当前选定的标志名称。

    struct ContentView: View {
        
        ...
        
        /// represents current selected button
        @State var currentSelectedFlagName: String
        
        var body: some View {
            List(flagList) { flagList in
                Button(action: {
    
                    /// set the property
                    currentSelectedFlagName = flagList.flagName
                    print("tapped")
                }) {
                    HStack(spacing: 15){
                        Image(flagList.flagName)
                            .resizable()
                            .scaledToFit()
                            .clipShape(Circle())
                            .frame(width: 30, height: 30, alignment: .trailing)
                        
                        Text(flagList.name)
                            .font(.system(size: 25, weight: .light, design: .default))
                        
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 2011-05-06
      • 2012-01-24
      • 2020-10-16
      • 2020-10-16
      • 1970-01-01
      相关资源
      最近更新 更多