将 SF Symbols 添加到 UIAlert 的标题中

adding SF Symbols to the title of UIAlert

我在将 SF 符号添加到标题时遇到问题。 SF Symbols 与标题文本重叠,谁能帮帮我

func uialert(){

    let alert = UIAlertController(title: "New User Created", message: " A new user has been created.", preferredStyle: .alert)
    let imgTitle = UIImage(systemName: "checkmark.circle")
    let imgViewTitle = UIImageView(frame: CGRect(x: 120, y: 10, width: 30, height: 30))
    imgViewTitle.image = imgTitle
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    alert.view.addSubview(imgViewTitle)
    self.present(alert, animated: true)
}

您可以使用 NSAttributedString 在其中获取复选标记。这是代码:

// 1. create the image for the attributed string
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(systemName: "checkmark.circle") 

// 2. Create the attributed string and append the image
let fullString = NSMutableAttributedString(string: "New User Created ")
fullString.append(NSAttributedString(attachment: imageAttachment))

// 3. Make the alert with an empty title and set the attributedTitle using .setValue
let alert = UIAlertController(title: "", message: " A new user has been created.", preferredStyle: .alert)
alert.setValue(fullString, forKey: "attributedTitle")

// 4. Present the alert
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)

结果:

有关属性字符串的更多信息,请参阅 Paul Hudson 撰写的一篇关于它们的精彩文章:https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example