使用Swift中的UIAlertController更改警报的标题和消息字体

时间:2014-11-06 10:31:51

标签: swift ios8 uialertcontroller

我正在尝试更改使用UIAlertController显示的警报的标题和消息字体 我试图使用NSAttributedStirng,但它给编译器错误,不能采用NSAttributed字符串而不是Stirng 我尝试过与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)

有人可以指导我如何实现这一目标?

4 个答案:

答案 0 :(得分:4)

我认为Apple从API中删除了attributionTitle和-message。它从未成为公众API的一部分,因此如果您使用它,Apple可能不允许您在应用商店中使用该应用。

您应该按原样使用UIAlertController。如果您想稍微自定义它,请参阅此NSHipster post。如果您想要更多控制,请创建要显示的自定义视图。

答案 1 :(得分:4)

Swift 3 版本:

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! )
    }
}

答案 2 :(得分:1)

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

答案 3 :(得分:0)

extension UIAlertController {
    func changeFont(view:UIView,font:UIFont) {
        for item in view.subviews {
            if item.isKindOfClass(UICollectionView) {
                let col = item as! UICollectionView
                for  row in col.subviews{
                    changeFont(row, font: font)
                }
            }
            if item.isKindOfClass(UILabel) {
                let label = item as! UILabel
                label.font = font
            }else {
                changeFont(item, font: font)
            }

        }
    }
    public override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        let font = UIFont(name: YourFontName, size: YourFontSize)
        changeFont(self.view, font: font! )
    }
}