Aft*_*ath 1 button selected uibutton swift swiftui
我正在尝试掌握 SwiftUI 概念(完成了 Apple 的 SwiftUI 教程),但在 UIKit 十年之后对我来说似乎很难。
我需要通过单击 HStack 中的多个按钮(UIKit 的isSelected)来切换它们的状态,并更改它们的字体和文本(在 UIKit 世界中,我会attributedText在if语句中使用属性检查isSelected属性,全部在@IBActionon TouchUpInside)。
我的第一个想法是在其操作块中获取 Button 的“引用”,但感觉这不是 SwiftUI 方式(甚至不可能)。我找到了使用 Configurator 及其 isPressed 属性的解决方案(这不是我搜索的内容),但我需要 Button 实际上像切换一样。SwiftUI 中是否有任何内置的 isSelected 替换,或者我必须使用 @State 或 @BindableObject 来制作我自己的 View 实现来封装一些手势识别器(看起来很丑)。提前致谢!
我想出了自定义视图,它像这样封装了 Button:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
如果这个解决方案不好,请告诉我为什么,我真的很感激。而且我还在为一个非常微不足道的问题而苦苦挣扎:如何将我的模型的数组元素映射到按钮(即如何检测确切地点击了哪个按钮),但我想我必须为此创建另一个问题。
| 归档时间: |
|
| 查看次数: |
5211 次 |
| 最近记录: |