如何为UIViewController弹窗扩展添加背景色与文本参数?
改进UIViewController的showAlert扩展,支持自定义背景色和提示文本
很简单,咱们直接给showAlert方法添加带默认值的参数,既能满足自定义需求,又不会破坏原来的调用逻辑。下面是修改后的完整代码,我会标注关键改动点:
extension UIViewController { // 1. 新增两个参数,同时设置默认值兼容原有调用 func showAlert(backgroundColor: UIColor = .brandSuccess(), message: String = "") { let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60)) // 2. 使用传入的背景色替换固定值 popupAlert.backgroundColor = backgroundColor // 3. 创建并配置提示标签,添加到弹窗视图 let alertLabel = UILabel(frame: CGRect(x: 16, y: 0, width: popupAlert.frame.width - 32, height: popupAlert.frame.height)) alertLabel.text = message alertLabel.textColor = .white // 你也可以把这个做成可选参数,让用户自定义 alertLabel.textAlignment = .center alertLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium) popupAlert.addSubview(alertLabel) let window = (UIApplication.shared.delegate as! AppDelegate).window! window.addSubview(popupAlert) // 动画逻辑保持不变 UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: { popupAlert.transform = .init(translationX: 0, y: 60) }) { (_) in UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: { popupAlert.transform = .init(translationX: 0, y: -60) }, completion: { (_) in popupAlert.removeFromSuperview() }) } } }
调用方式示例
- 保留原有默认效果:
showAlert() - 仅自定义背景色:
showAlert(backgroundColor: .systemRed) - 仅自定义提示文本:
showAlert(message: "文件上传成功!") - 同时自定义背景色和文本:
showAlert(backgroundColor: .systemBlue, message: "设置已保存")
额外优化建议(可选)
如果想让弹窗适配更多场景(比如长文本换行),可以用AutoLayout替代固定frame来布局标签:
// 替换原来的label创建代码 let alertLabel = UILabel() alertLabel.translatesAutoresizingMaskIntoConstraints = false alertLabel.text = message alertLabel.textColor = .white alertLabel.textAlignment = .center alertLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium) alertLabel.numberOfLines = 0 // 允许文本换行 popupAlert.addSubview(alertLabel) // 添加约束 NSLayoutConstraint.activate([ alertLabel.leadingAnchor.constraint(equalTo: popupAlert.leadingAnchor, constant: 16), alertLabel.trailingAnchor.constraint(equalTo: popupAlert.trailingAnchor, constant: -16), alertLabel.centerYAnchor.constraint(equalTo: popupAlert.centerYAnchor), // 标签高度不超过弹窗高度,避免内容溢出 alertLabel.heightAnchor.constraint(lessThanOrEqualTo: popupAlert.heightAnchor, constant: -8) ])
这样即使文本较长,也能自动换行显示,不会被截断~
内容的提问来源于stack exchange,提问作者unicorn_surprise
相关产品推荐
相关产品推荐

