SwiftUI 按钮选择

标签 swift button uibutton swiftui selected

我正在尝试掌握 SwiftUI 概念(完成了 Apple 的 SwiftUI 教程),但在 UIKit 十年之后这对我来说似乎很难。

我需要通过点击它们来切换 HStack 中多个按钮的状态(UIKit 的 isSelected),并更改它们的字体和文本(在 UIKit 世界中我会使用 attributedText if 语句中的属性检查 isSelected 属性,全部在 TouchUpInside 上的 @IBAction 中。

我的第一个想法是在其操作 block 中获取 Button 的“引用”,但感觉这不是 SwiftUI 的方式(甚至不可能)。我找到了使用 Configurator 及其 isPressed 属性的解决方案(这不是我要搜索的),但我需要 Button 的行为实际上像切换一样。 SwiftUI 中是否有任何内置的 isSelected 替换,或者我必须使用 @State 或 @BindableObject 制作我自己的 View 实现,这将封装一些手势识别器(看起来非常丑陋)。提前致谢!

最佳答案

我想出了自定义 View ,它是这样封装按钮的:

    import SwiftUI

struct SelectableButtonStyle: ButtonStyle {

    var isSelected = false

    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .frame(width: 60.0, height: 60.0, alignment: .center)
            .padding()
            .background(Color(#colorLiteral(red: 1, green: 0.8980392157, blue: 0.7058823529, alpha: 1)))
            .clipShape(RoundedRectangle(cornerRadius: isSelected ? 16.0 : 0.0))
            .overlay(RoundedRectangle(cornerRadius: isSelected ? 16.0 : 0.0).stroke(lineWidth: isSelected ? 2.0 : 0.0).foregroundColor(Color.pink))
            .animation(.linear)
    }
}


struct StatedButton<Label>: View where Label: View {


    private let action: (() -> ())?

    private let label: (() -> Label)?

    @State var buttonStyle = SelectableButtonStyle()

    init(action: (() -> ())? = nil, label: (() -> Label)? = nil) {
        self.action = action
        self.label = label
    }

    var body: some View {
        Button(action: {
            self.buttonStyle.isSelected = !self.buttonStyle.isSelected
            self.action?()
            print("isSelected now is \(self.buttonStyle.isSelected ? "true" : "false")")
        }) {
            label?()
        }
        .buttonStyle(buttonStyle)
    }    
}

如果这个解决方案不好,请告诉我为什么,我真的很感激。而且我还在为非常琐碎的问题而苦苦挣扎:如何将模型的数组元素映射到按钮(即如何检测究竟是哪个按钮被点击),但我认为我必须为此创建另一个问题。

关于SwiftUI 按钮选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617775/

相关文章:

android - 我怎么不能同时点击多个按钮?

swift - 如何枚举 String 类型的枚举?

ios - 在点击手势时显示 UIPickerView

android - MultiAutoCompleteTextView Android 开发中的按钮

objective-c - 在方法中保留变量

ios - 带有背景图像按钮的圆形边框 swift

iphone - UIButton和setImage : not working consistently - inconsistent

ios - 每次滚动时,tableviewcell 中的 alpha 渐变都会变暗

ios - 尝试在 Swift 2.0 中解析 json 数据时出现错误?

java - 单击时更改按钮的背景颜色,然后打开一个新 Activity