Johnny Lynch
Johnny Lynch

Reputation: 21

Can I add NSAttributedString in UIMenuItem's title instead of String?

I would like to add NSAttributedString in UIMenuItem's title instead of String, but I don't see any possible way of doing this. Is it even possible to maybe subclass UIMenuItem or something else to achieve this? I saw that on Telegram application on iOS they achieved something like this. Image with UIMenuItem from Telegram.

Upvotes: 0

Views: 421

Answers (1)

Wilfried Josset
Wilfried Josset

Reputation: 1256

This should allow you to use NSAttributedString for the title of your UIMenuItem:

import UIKit

class CustomUIMenuItem: UIMenuItem {
    init(titleAttributedString: NSAttributedString, action: Selector) {
        super.init(title: titleAttributedString.string, action: action)
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let item = CustomUIMenuItem(titleAttributedString: NSAttributedString(string: "Menu Title"), action: #selector(testFunction))
        UIMenuController.shared.menuItems = [item]
    }

    @objc func testFunction() {
        print("Success")
    }
}

Upvotes: 0

Related Questions