我有两个buttonStyle,mainButtonOn和mainButtonOff。我希望我的按钮根据其切换状态使用一个按钮。以下代码引发错误“无法推断复杂的闭包返回类型;明确添加类型以消除歧义。”
我是SwiftUI的新手,因此,如果您愚蠢地回答问题,那么如果您能看到问题,我会很乐意。谢谢大家。
import SwiftUI
struct ContentView: View {
var displayTime = "Ahoy"
func getTime(oldTime: Int, addedTime: Int) -> Int {
return oldTime + addedTime
}
@State var hoursOn:Bool = true
struct mainButtonOff: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.frame(width: 110, height: 35, alignment: .center)
.background(Color.white)
.foregroundColor(Color.gray)
.cornerRadius(30)
.overlay(RoundedRectangle(cornerRadius: 30) .stroke(Color.gray, lineWidth: 1))
}
}
struct mainButtonOn: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.frame(width: 110, height: 35, alignment: .center)
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(30)
.overlay(RoundedRectangle(cornerRadius: 30) .stroke(Color.blue, lineWidth: 1))
}
}
var body: some View {
let displayTime = String(getTime(oldTime: 15, addedTime: 10)) // get time and turn it into a string
return VStack { // ***** ERROR: Unable to infer complex closure return type; add explicitly type to disambiguate.
//Spacer()
Text(displayTime)
//Spacer()
Button(action: {self.hoursOn.toggle()}) {
Text("Hours")
.font(.headline)
}
.buttonStyle(self.hoursOn ? mainButtonOn() : mainButtonOff())
//.buttonStyle(mainButtonOff()) // <= USING THIS LINE INSTEAD THROWS NO ERROR
}
}
}
一种方法是绕过问题:
if self.hoursOn {
Button(action: {self.hoursOn.toggle()}) {
Text("Hours").font(.headline)
}.buttonStyle(mainButtonOn())
} else {
Button(action: {self.hoursOn.toggle()}) {
Text("Hours").font(.headline)
}.buttonStyle(mainButtonOff())
}
另一个更简洁的方法是这样:
struct mainButtonOnOff: ButtonStyle {
let onoff: Bool
init(_ switsh: Bool) {
self.onoff = switsh
}
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.frame(width: 110, height: 35, alignment: .center)
.background(self.onoff ? Color.blue : Color.white)
.foregroundColor(self.onoff ? Color.white : Color.gray)
.cornerRadius(30)
.overlay(RoundedRectangle(cornerRadius: 30) .stroke(self.onoff ? Color.blue : Color.gray, lineWidth: 1))
}
}
and:
Button(action: {self.hoursOn.toggle()}) {
Text("Hours") .font(.headline)
}.buttonStyle(mainButtonOnOff(self.hoursOn))