Swift中按钮点击传值异常:使用if判断始终打印首个值
Swift按钮点击值传递问题解决
你的代码核心问题是没有判断当前点击的按钮,而是固定判断zeroPctButton和tenPctButton的标题——只要zeroPctButton的标题是"0%",不管你点哪个按钮,都会走第一个分支打印"0.0"。
修复方案:
给所有需要响应点击的按钮绑定同一个点击方法,通过方法参数获取当前点击的按钮,再根据它的标题做判断。
步骤1:绑定点击事件
给每个按钮添加点击事件(代码绑定或Storyboard绑定均可):
// 代码示例:给按钮绑定点击方法 zeroPctButton.addTarget(self, action: #selector(onPctButtonTap(_:)), for: .touchUpInside) tenPctButton.addTarget(self, action: #selector(onPctButtonTap(_:)), for: .touchUpInside) // 对应else分支的按钮(比如20%的按钮)也需要绑定 twentyPctButton.addTarget(self, action: #selector(onPctButtonTap(_:)), for: .touchUpInside)
步骤2:实现点击方法
在方法里获取当前点击按钮的标题,再做判断:
@objc func onPctButtonTap(_ sender: UIButton) { // 安全获取按钮标题,避免强制解包崩溃 guard let buttonTitle = sender.titleLabel?.text else { print("无法获取按钮标题") return } // 根据标题判断输出对应值 if buttonTitle == "0%" { print("0.0") } else if buttonTitle == "10%" { print("0.1") } else if buttonTitle == "20%" { print("0.2") } else { print("未知百分比按钮被点击") } }
也可以用更简洁的switch写法:
@objc func onPctButtonTap(_ sender: UIButton) { guard let buttonTitle = sender.titleLabel?.text else { print("无法获取按钮标题") return } switch buttonTitle { case "0%": print("0.0") case "10%": print("0.1") case "20%": print("0.2") default: print("未知百分比按钮被点击") } }
这样修改后,点击不同按钮时,会根据当前点击按钮的标题输出对应的值,不会再固定打印第一个分支的内容。
内容的提问来源于stack exchange,提问作者Francesco5177
相关产品推荐
相关产品推荐

