#ios #swift #alert
#iOS #swift #предупреждение
Вопрос:
Я хочу показать вид изображения рядом с заголовком предупреждения. для этого я добавил приведенный ниже код, но моя проблема в том, что он показывает слишком много места между заголовком предупреждения и видом изображения.
let attributedString = NSAttributedString(string: "Delete", attributes: [NSAttributedString.Key.foregroundColor : UIColor(named: "TextColor")!])
let attributedMessageString = NSAttributedString(string: "Should the set heating time really be deleted?", attributes: [NSAttributedString.Key.foregroundColor : UIColor(named: "TextColor")!])
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
alert.setValue(attributedString, forKey: "attributedTitle")
alert.setValue(attributedMessageString, forKey: "attributedMessage")
alert.addAction(UIAlertAction(title: "Abort", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Delete", style: .default, handler: {(action:UIAlertAction!) in
self.startTimeTextField.text = "--:--"
}))
let imgTitle = UIImage(named:"ArrowUpImage")
let imgViewTitle = UIImageView(frame: CGRect(x: alert.view.center.x , y: 15, width: 30, height: 30))
imgViewTitle.image = imgTitle
alert.view.addSubview(imgViewTitle)
let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
subview.backgroundColor = UIColor(named: "BackgroundColor")
alert.view.tintColor = UIColor(named: "SpecialColor")
self.viewController.present(alert, animated: true, completion: nil)
Я хочу, чтобы мой вид предупреждения выглядел так, как показано на рисунке ниже (заголовок предупреждения и вид изображения между пробелами составляют всего 10).
Не могли бы вы мне помочь?
Комментарии:
1. Я бы не стал связываться с
UIAlertController
тем, что указано в документе:The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.
Ответ №1:
используйте NSTextAttachment —
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "imageName")
let imageOffsetY: CGFloat = -(imageAttachment.image!.size.height/4)
imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: imageAttachment.image!.size.width, height: imageAttachment.image!.size.height)
let attachmentString = NSAttributedString(attachment: imageAttachment)
let attributedString = NSMutableAttributedString(string: "Delete ")
attributedString.append(attachmentString)
alert.setValue(attributedString, forKey: "attributedTitle")
Комментарии:
1. Можем ли мы центрировать горизонтально вложение изображения с заголовком предупреждения?