Swift 3:如何在自定义UIView弹窗中添加文本/Label
嘿,我完全懂你这会儿的困扰——自己撸了个基于UIView的弹窗框架,结果在showAlert()里直接加Label死活显示不出来,用外部方法拿文本倒是能显示,但弹窗又关不上了。别慌,咱们直接从根上解决:在showAlert()里正确把Label加到弹窗上,同时保证关闭逻辑稳得一批,而且完全不用UIAlertController。
核心要点梳理
首先得明确几个关键:
- 你的弹窗UIView必须已经正确初始化,并且能被添加到父视图(比如App的keyWindow或者当前ViewController的view)
- 要在
showAlert()内部创建Label、配置样式、设置布局约束,最后把它直接添加到弹窗View上,而不是错误地加到其他视图层级 - 弹窗的关闭逻辑(比如点击关闭按钮、点击背景遮罩)必须绑定在弹窗View本身,不能因为添加子视图被破坏
完整代码示例
先假设你已经有一个基础的弹窗类CustomAlertView,我们先完善它的基础结构:
import UIKit class CustomAlertView: UIView { // 可选的关闭按钮,按需添加 private let closeButton: UIButton = { let btn = UIButton(type: .system) btn.setTitle("关闭", for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium) btn.translatesAutoresizingMaskIntoConstraints = false return btn }() override init(frame: CGRect) { super.init(frame: frame) setupBaseStyle() } required init?(coder: NSCoder) { super.init(coder: coder) setupBaseStyle() } private func setupBaseStyle() { // 弹窗基础样式:背景、圆角、阴影 backgroundColor = .white layer.cornerRadius = 12 layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.3 layer.shadowOffset = .zero layer.shadowRadius = 8 // 添加并布局关闭按钮 addSubview(closeButton) closeButton.addTarget(self, action: #selector(closeAlert), for: .touchUpInside) NSLayoutConstraint.activate([ closeButton.topAnchor.constraint(equalTo: topAnchor, constant: 16), closeButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16) ]) } // 弹窗关闭逻辑:带动画淡出并移除 @objc func closeAlert() { UIView.animate(withDuration: 0.3) { self.alpha = 0 } completion: { _ in self.removeFromSuperview() // 顺便移除背景遮罩(如果有的话) self.superview?.subviews.forEach { subview in if subview.backgroundColor?.alpha == 0.5 { subview.removeFromSuperview() } } } } }
接下来是你要的showAlert()函数,直接在里面创建并添加Label:
func showAlert() { // 1. 创建弹窗实例,设置初始大小(后续可以用约束调整,这里先给个固定值) let alertView = CustomAlertView(frame: CGRect(x: 0, y: 0, width: 280, height: 180)) alertView.translatesAutoresizingMaskIntoConstraints = false // 2. 创建要显示的文本Label let messageLabel = UILabel() messageLabel.text = "这是你要在弹窗里显示的固定文本内容,支持多行哦~" messageLabel.numberOfLines = 0 messageLabel.textAlignment = .center messageLabel.font = UIFont.systemFont(ofSize: 16) messageLabel.textColor = .darkText messageLabel.translatesAutoresizingMaskIntoConstraints = false // 3. 把Label添加到弹窗View上 alertView.addSubview(messageLabel) // 4. 给Label设置布局约束,保证它在弹窗里正确显示 NSLayoutConstraint.activate([ messageLabel.topAnchor.constraint(equalTo: alertView.topAnchor, constant: 40), messageLabel.leadingAnchor.constraint(equalTo: alertView.leadingAnchor, constant: 20), messageLabel.trailingAnchor.constraint(equalTo: alertView.trailingAnchor, constant: -20), messageLabel.bottomAnchor.constraint(lessThanOrEqualTo: alertView.bottomAnchor, constant: -20) ]) // 5. 把弹窗添加到App的keyWindow(也可以用当前ViewController的view) guard let keyWindow = UIApplication.shared.keyWindow else { return } // 添加背景遮罩,增强弹窗层次感 let backgroundMask = UIView(frame: keyWindow.bounds) backgroundMask.backgroundColor = UIColor.black.withAlphaComponent(0.5) backgroundMask.addGestureRecognizer(UITapGestureRecognizer(target: alertView, action: #selector(CustomAlertView.closeAlert))) keyWindow.addSubview(backgroundMask) // 添加弹窗并设置居中约束 keyWindow.addSubview(alertView) NSLayoutConstraint.activate([ alertView.centerXAnchor.constraint(equalTo: keyWindow.centerXAnchor), alertView.centerYAnchor.constraint(equalTo: keyWindow.centerYAnchor), alertView.widthAnchor.constraint(equalToConstant: 280), alertView.heightAnchor.constraint(greaterThanOrEqualToConstant: 120) ]) // 弹窗显示动画 alertView.alpha = 0 backgroundMask.alpha = 0 UIView.animate(withDuration: 0.3) { alertView.alpha = 1 backgroundMask.alpha = 1 } }
为什么之前会出问题?
- 你之前在
showAlert()里加Label没显示,大概率是没给Label设置正确的约束(比如用了frame但弹窗用的是AutoLayout,或者Label被加到了弹窗之外的视图上) - 用外部函数获取文本后弹窗关不了,一般是外部方法不小心持有了弹窗的引用,或者破坏了弹窗关闭逻辑的target/action绑定。现在直接在
showAlert()内部操作,所有逻辑都围绕弹窗View本身,不会出现这种问题。
内容的提问来源于stack exchange,提问作者Kanav Batra
相关产品推荐
相关产品推荐

