问题
我们在创建一个Button的时候,通常会给它一个背景色,这样的按钮看起来更醒目
于是我们实现该按钮如下
Button(action: {
self.alertTitle = "兑换"
self.showAlert = true
}) {
Text("兑换")
}
.foregroundColor(.blue)
.frame(width: UIScreen.main.bounds.width - 40, height: 45, alignment: .center)
.background(Color("ButtonBackColor"))
.cornerRadius(10.0)
效果图
一切看上去很美好,可是。。。
问题出现了,当我们点击“兑换”两个字的位置时,可以正常触发点击事件,但是点击按钮其他区域的时候,没有任何反应。
解决
该问题是因为,我们将按钮的背景色设置在Button上,但是Button实际上是由其内部的Text视图触发的,所以,我们将修饰符用在内部的Text上即可
如下代码正常点击
Button(action: {
self.alertTitle = "兑换"
self.showAlert = true
}) {
Text("兑换")
.foregroundColor(.blue)
.frame(width: UIScreen.main.bounds.width - 40, height: 45, alignment: .center)
.background(Color("ButtonBackColor"))
.cornerRadius(10.0)
}