我试图掌握SwiftUI的概念(完成了苹果的SwiftUI教程),但在UIKit十年之后,这对我来说似乎很难。
我需要通过单击HStack中的多个按钮( UIKit的isSelected)来切换它们的状态,并更改它们的字体和文本(在UIKit世界中,我将在if语句examinig isSelected属性中使用attributedText属性,全部在@IBAction on TouchUpInside中)。
我的第一个想法是在它的action块中获得Button的“引用”,但感觉它不是SwiftUI的方式(甚至是不可能的)。我找到了使用Configurator及其isPressed属性的解决方案(这不是我要搜索的),但是我需要按钮才能像切换一样运行。在isSelected中是否存在内置的SwiftUI替换,或者我必须使用@State或@BindableObject来实现自己的视图,这将封装一些手势识别器(看起来很难看)。提前感谢!
发布于 2019-08-29 13:25:32
我想出了一个自定义视图,它像这样封装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)
}
}如果这个解决方案不好,请告诉我,为什么,我真的很感激。此外,我还在努力解决非常琐碎的问题:如何将我的模型的数组元素映射到按钮(即如何检测哪个按钮被点击),但我认为我必须为此创建另一个问题。
发布于 2020-08-05 06:58:21
我有个简单的方法。
@State var selected = false
func createButton() -> some View {
Button(action: {
self.selected.toggle()
}, label: {
Text("Hello World")
.padding(.all, 5)
.background(selected ? Color.blue : Color.white)
.foregroundColor(selected ? Color.white : Color.blue)
})
.overlay(
RoundedRectangle(cornerRadius: 4)
.stroke(Color.blue, lineWidth: 1)
)
}发布于 2021-12-21 23:31:26
您可以创建一个自定义ButtonStyle并基于isPressed修改配置的标签
struct CustomButton: View {
var body: some View {
Button {
// action
} label: {
Text("Button")
}
.buttonStyle(CustomStyle())
}
}
struct CustomStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.background(configuration.isPressed ? .green : .black)
}
}https://stackoverflow.com/questions/57617775
复制相似问题