如何在UIAlertController动作表中右对齐UIAlertAction的图片?
UIAlertAction 文本左对齐+图片右对齐实现方案
方案一:基于富文本的实现(无私有API,推荐)
通过将图片作为富文本附件追加到标题右侧,同时设置文本左对齐,这种方式不依赖系统私有视图结构,兼容性更强。
步骤代码:
// 准备目标图片与标题文本 let targetImage = UIImage(named: "your_image")! let actionTitle = "Text 1" // 按需调整图片尺寸 let imageSize = CGSize(width: 20, height: 20) UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale) targetImage.draw(in: CGRect(origin: .zero, size: imageSize)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() // 构建富文本内容 let attributedTitle = NSMutableAttributedString(string: actionTitle) let imageAttachment = NSTextAttachment() imageAttachment.image = resizedImage // 调整图片与文本的垂直对齐偏移 imageAttachment.bounds = CGRect(x: 0, y: -4, width: imageSize.width, height: imageSize.height) // 给图片和标题之间添加空格分隔 attributedTitle.append(NSAttributedString(string: " ")) attributedTitle.append(NSAttributedString(attachment: imageAttachment)) // 设置文本左对齐 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .left attributedTitle.addAttribute( .paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedTitle.length) ) // 创建UIAlertAction并赋值富文本标题 let firstAction = UIAlertAction(title: nil, style: .default) { _ in // 点击事件处理逻辑 } firstAction.setValue(attributedTitle, forKey: "attributedTitle")
方案二:修改内部视图实现(依赖私有结构,需谨慎)
通过遍历UIAlertController的子视图,找到UIAlertAction对应的图片视图,调整其约束使其右对齐。这种方式依赖系统内部视图结构,iOS版本更新可能导致失效。
步骤代码:
// 创建UIAlertAction并设置文本左对齐 let firstAction = UIAlertAction(title: "Text 1", style: .default) { _ in // 点击事件处理逻辑 } firstAction.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment") firstAction.setValue(UIImage(named: "your_image"), forKey: "image") // 创建并弹出AlertController let alert = UIAlertController(title: "提示", message: "这是测试弹窗", preferredStyle: .actionSheet) alert.addAction(firstAction) present(alert, animated: true) { // 递归查找Action对应的图片视图 func findActionImageView(in view: UIView) -> UIImageView? { if let imageView = view as? UIImageView, imageView.image != nil { return imageView } for subview in view.subviews { if let targetView = findActionImageView(in: subview) { return targetView } } return nil } // 调整图片视图到右侧 if let imageView = findActionImageView(in: alert.view) { imageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageView.trailingAnchor.constraint(equalTo: imageView.superview!.trailingAnchor, constant: -16), imageView.centerYAnchor.constraint(equalTo: imageView.superview!.centerYAnchor) ]) } }
内容的提问来源于stack exchange,提问作者theEagleDev
相关产品推荐
相关产品推荐

