UIAlertController custom font, size, color

后端 未结 25 1973
遥遥无期
遥遥无期 2020-11-22 09:06

I am using new UIAlertController for showing alerts. I have this code:

// nil titles break alert interface on iOS 8.0, so we\'ll be using empty strings
UIAle         


        
25条回答
  •  时光取名叫无心
    2020-11-22 09:56

    A Swift translation of the @dupuis2387 answer. Worked out the syntax to set the UIAlertController title's color and font via KVC using the attributedTitle key.

    let message = "Some message goes here."
    let alertController = UIAlertController(
        title: "", // This gets overridden below.
        message: message,
        preferredStyle: .Alert
    )
    let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ -> Void in
    }
    alertController.addAction(okAction)
    
    let fontAwesomeHeart = "\u{f004}"
    let fontAwesomeFont = UIFont(name: "FontAwesome", size: 17)!
    let customTitle:NSString = "I \(fontAwesomeHeart) Swift" // Use NSString, which lets you call rangeOfString()
    let systemBoldAttributes:[String : AnyObject] = [ 
        // setting the attributed title wipes out the default bold font,
        // so we need to reconstruct it.
        NSFontAttributeName : UIFont.boldSystemFontOfSize(17)
    ]
    let attributedString = NSMutableAttributedString(string: customTitle as String, attributes:systemBoldAttributes)
    let fontAwesomeAttributes = [
        NSFontAttributeName: fontAwesomeFont,
        NSForegroundColorAttributeName : UIColor.redColor()
    ]
    let matchRange = customTitle.rangeOfString(fontAwesomeHeart)
    attributedString.addAttributes(fontAwesomeAttributes, range: matchRange)
    alertController.setValue(attributedString, forKey: "attributedTitle")
    
    self.presentViewController(alertController, animated: true, completion: nil)
    

提交回复
热议问题