adding SF Symbols to the title of UIAlert
Asked Answered
L

1

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)
}
Lenticularis answered 22/4, 2020 at 20:41 Comment(2)
Adding your own views to an alert controller's view is not supported. From the docs: "The view hierarchy for this class is private and must not be modified."Florio
can I add an image in the title ?Lenticularis
I
6

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

Inheritor answered 22/4, 2020 at 21:29 Comment(2)
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.Basenji
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: #44130847Shawnee

© 2022 - 2024 — McMap. All rights reserved.