5

I have a problem adding SF Symbols to the title. SF Symbols is overlap with title text can someone help me

enter image description here

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)
}
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51
  • Adding your own views to an alert controller's view is not supported. From the [docs](https://developer.apple.com/documentation/uikit/uialertcontroller): "The view hierarchy for this class is private and must not be modified." – TylerP Apr 22 '20 at 21:05
  • can I add an image in the title ? – NinjaDeveloper Apr 22 '20 at 21:10

1 Answers1

7

You can use NSAttributedString to get the checkmark in there. Here's the code:

// 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)

And the result:

successful alert

For more info on attributed strings here's a great article on them by Paul Hudson: https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example

thecoolwinter
  • 861
  • 7
  • 22
  • 1
    This looks like a great solution, I tried to do the same for a `UIAlertAction` but it doesn't recognise the selector unfortunately. I ended up just using the ✓ emoji. – Leon Feb 15 '21 at 12:14
  • 1
    Just a note for anyone considering using this - the `alert.setValue(fullString, forKey: "attributedTitle")` API is not official, so while it works currently on iOS 15, there's no guarantee it would work in the future, and might even crash. There's a way to call it safer and have a fallback, described here: https://stackoverflow.com/questions/44130347/uialertcontroller-set-attributed-messages – Nikolay Suvandzhiev Apr 01 '22 at 20:00