I am trying to change the title and message font for an alert shown using UIAlertController I am trying to do using an NSAttributedStirng, but it gives compiler error that a NSAttributed string cannot be taken instead of Stirng I tried something similar to this
var title_attrs = [NSFontAttributeName : CustomFonts.HELVETICA_NEUE_MEDIUM_16]
var msg_attrs = [NSFontAttributeName : CustomFonts.HELVETICA_NEUE_REGULAR_14]
var title = NSMutableAttributedString(string:"Done", attributes:title_attrs)
var msg = NSMutableAttributedString(string:"The job is done ", attributes:msg_attrs)
let alertController = UIAlertController(title: title, message: title , preferredStyle: UIAlertControllerStyle.Alert)
Can someone guide me how can I achieve this?
Swift 3 Version:
extension UIAlertController {
func changeFont(view: UIView, font:UIFont) {
for item in view.subviews {
if item.isKind(of: UICollectionView.self) {
let col = item as! UICollectionView
for row in col.subviews{
changeFont(view: row, font: font)
}
}
if item.isKind(of: UILabel.self) {
let label = item as! UILabel
label.font = font
}else {
changeFont(view: item, font: font)
}
}
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let font = YOUR_FONT
changeFont(view: self.view, font: font! )
}
}
I think Apple removed the attributedTitle and -message from the API. It was never part of the public API so it might be that Apple will not allow your app in the app store if you used it.
You should use the UIAlertController as is. If you want to customise it a bit see this NSHipster post. If you want more control, create a custom View to display.
let myString = "Alert Title"
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:myString.characters.count))
alertController.setValue(myMutableString, forKey: "attributedTitle")
alertController.setValue(myMutableString, forKey: "attributedMessage")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With