You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift:实现UIAlertAction布尔状态存储、颜色切换及弹窗常驻

实现UIAlertAction点击切换颜色且不关闭弹窗

要实现你要的效果,需要解决两个核心问题:阻止UIAlertAction点击后自动关闭弹窗,以及动态修改按钮颜色并维护选中状态。以下是修改后的代码和关键说明:

关键思路

  • 用布尔变量记录按钮的选中状态(isBestFiendSelected)
  • 创建UIAlertAction时不设置handler,避免默认触发弹窗关闭
  • 遍历弹窗视图找到目标按钮,添加自定义点击事件处理逻辑
  • 在点击事件中切换状态,修改按钮文字颜色(绿色代表选中,系统默认颜色代表未选中)

修改后的完整代码

@objc func addSong(_ sender: UIBarButtonItem) {
    var titleTextField = UITextField()
    var isBestFiendSelected = false // 记录选中状态
    
    let alert = UIAlertController(title: "Enter name", message: "", preferredStyle: .alert)
    
    let createAction = UIAlertAction(title: "Create", style: .default) { [self] (action) in
        // 这里保留你原来的Create按钮逻辑
    }
    
    alert.addTextField { (alertTextField) in
        titleTextField = alertTextField
    }
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) { (action) in
        self.dismiss(animated: true, completion: nil)
    }
    
    // 创建Best Feind按钮,handler设为nil避免自动关闭弹窗
    let bestFiendAction = UIAlertAction(title: "Best Feind", style: .default, handler: nil)
    alert.addAction(bestFiendAction)
    alert.addAction(createAction)
    alert.addAction(cancelAction)
    
    // 弹窗显示后,找到Best Feind对应的按钮并添加自定义点击事件
    DispatchQueue.main.async {
        guard let buttons = alert.view.subviews.first?.subviews.first?.subviews.filter({ $0 is UIButton }) as? [UIButton] else {
            return
        }
        // 找到标题匹配的按钮
        if let bestFiendButton = buttons.first(where: { $0.titleLabel?.text == "Best Feind" }) {
            bestFiendButton.addTarget(self, action: #selector(self.bestFiendButtonTapped(_:)), for: .touchUpInside)
            // 初始化按钮状态和颜色
            bestFiendButton.isSelected = isBestFiendSelected
            bestFiendButton.setTitleColor(isBestFiendSelected ? .green : nil, for: .normal)
        }
    }
    
    present(alert, animated: true, completion: nil)
}

// 处理Best Feind按钮的自定义点击事件
@objc private func bestFiendButtonTapped(_ sender: UIButton) {
    sender.isSelected.toggle()
    // 切换文字颜色:选中时绿色,未选中时恢复系统默认颜色
    sender.setTitleColor(sender.isSelected ? .green : nil, for: .normal)
    
    // 这里可以根据sender.isSelected的值(true/false)执行你需要的逻辑
    // 例如修改releaseDateTextField的样式,若要操作它需将其设为类属性或调整变量作用域
}

注意事项

  • 若需在点击事件中操作releaseDateTextField,建议将其声明为类属性,或调整变量作用域确保能被访问
  • 遍历弹窗视图找按钮的方式依赖UIAlertController的内部视图结构,当前主流iOS版本可正常工作,后续若苹果修改内部结构可能需要调整
  • 设置nil作为按钮文字颜色会恢复系统默认样式,适配亮色/暗色主题

内容的提问来源于stack exchange,提问作者Max Madill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 00:06:09