【问题标题】:adding SF Symbols to the title of UIAlert在 UIAlert 的标题中添加 SF Symbols
【发布时间】:2020-08-06 01:00:18
【问题描述】:

在标题中添加 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)
}

【问题讨论】:

  • 不支持将您自己的视图添加到警报控制器的视图中。来自docs:“此类的视图层次结构是私有的,不得修改。”
  • 我可以在标题中添加图片吗?

标签: swift ios13 uialertcontroller sf-symbols


【解决方案1】:

您可以使用 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

【讨论】:

  • 这看起来是一个很好的解决方案,我尝试对UIAlertAction 做同样的事情,但不幸的是它无法识别选择器。我最终只使用了 ✓ 表情符号。
猜你喜欢
  • 2021-07-11
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2021-10-16
  • 2020-07-02
  • 1970-01-01
相关资源
最近更新 更多