如何在UIAlertController中将图片设为标题并实现消息正常排版
问题原因
你现在的排版异常核心是两个问题:
- 图片位置用了硬编码的x坐标180,不同设备屏幕宽度不同,无法做到全局居中,自然没法对齐下方的文字
- 直接将图片视图加到alert的根视图上,没有和系统自带的消息文本做排版关联,系统渲染消息文本时不会预留图片的位置,必然会出现错位、重叠的问题
另外你通过多层subviews下标取视图改背景色的写法非常不稳定,iOS系统版本迭代后视图层级变化会直接导致闪退,不建议使用。
最优解决方案:富文本拼接(推荐)
用富文本拼接图片+文字,直接作为UIAlertController的message,系统会自动处理排版,天然保证图片在文字正上方居中,适配所有设备:
let alrt = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // 拼接图片+文字的富文本 let attributedContent = NSMutableAttributedString() // 添加图片部分 let imageAttachment = NSTextAttachment() imageAttachment.image = Icon // 调整图片大小和偏移,让它居中显示 imageAttachment.bounds = CGRect(x: 0, y: 0, width: 35, height: 35) // 让图片整体居中 let imageAttributed = NSAttributedString(attachment: imageAttachment) let paraStyle = NSMutableParagraphStyle() paraStyle.alignment = .center attributedContent.append(imageAttributed) attributedContent.addAttribute(.paragraphStyle, value: paraStyle, range: NSRange(location: 0, length: imageAttributed.length)) // 加换行,把图片和文字分开 attributedContent.append(NSAttributedString(string: "\n\n")) // 添加文字部分 let textAttr: [NSAttributedString.Key: Any] = [ .font: UIFont(name: "Poppins-medium", size: 20) ?? UIFont.systemFont(ofSize: 20, weight: .medium), .foregroundColor: UIColor.white, .paragraphStyle: paraStyle ] attributedContent.append(NSAttributedString(string: msg, attributes: textAttr)) // 把富文本设置给alert alrt.setValue(attributedContent, forKey: "attributedMessage") // 按钮部分保持不变 let btn1 = UIAlertAction(title: "While using the app.", style: .default,handler: nil) let btn2 = UIAlertAction(title: "Only this time.", style: .default,handler: nil) let btn3 = UIAlertAction(title: "Deny", style: .default,handler: nil) alrt.addAction(btn1) alrt.addAction(btn2) alrt.addAction(btn3) alrt.view.tintColor = UIColor.blue // 改背景色的稳妥写法:遍历匹配视图,不要硬写下标 for subview in alrt.view.subviews.first?.subviews.first?.subviews ?? [] { subview.backgroundColor = UIColor.black } fromView.present(alrt, animated: true, completion: nil)
可选方案:手动加子视图(用自动布局)
如果坚持要手动添加UIImageView实现,不要用硬编码frame,改用自动布局约束:
// 先给消息文本加换行,预留图片位置 let adjustedMsg = "\n\n\n" + msg let alrt = UIAlertController(title:nil, message: adjustedMsg, preferredStyle:.actionSheet) alrt.setMessage(font: UIFont(name: "Poppins-medium", size: 20), color: UIColor.white) // 其他按钮逻辑不变... // 初始化图片视图,用自动布局 let imageView = UIImageView(image: Icon) imageView.translatesAutoresizingMaskIntoConstraints = false alrt.view.addSubview(imageView) // 加约束:水平居中,距离顶部10pt,宽高35pt NSLayoutConstraint.activate([ imageView.centerXAnchor.constraint(equalTo: alrt.view.centerXAnchor), imageView.topAnchor.constraint(equalTo: alrt.view.topAnchor, constant: 10), imageView.widthAnchor.constraint(equalToConstant: 35), imageView.heightAnchor.constraint(equalToConstant: 35) ]) fromView.present(alrt, animated: true, completion: nil)
内容的提问来源于stack exchange,提问作者iOSFresher
相关产品推荐
相关产品推荐

