iOS[swift] 修改UIAlertController的messageText样式

ios 原生的弹窗 messageText默认是居中的,特别丑,UI妹子提了个需求要让弹框里的文字居左对齐,所以在stackOverFlow上查了一下, 原理大概是使用KVC来修改这个样式,别的不多说了上代码:

let tipsMessage = "一只风流的dog一只风流的dog一只风流的dog一只风流的dog\n一只风流的dog一只风流的dog一只风流的dog一只风流的dog一只风流的dog一只风流的dog\n一只风流的dog一只风流的dog一只风流的dog一只风流的dog一只风流的dog"
let myAlert = UIAlertController(title: "", message: tipsMessage, preferredStyle: UIAlertControllerStyle.alert)
let sureAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.default, handler: {[unowned self] (alertAction) in
    //do someting...
})
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: {[unowned self] (alertAction) in
    //do someting...
})
myAlert.addAction(cancelAction)
myAlert.addAction(sureAction)
let paragraphStyle = NSMutableParagraphStyle() // 注意一定要是mutable!
paragraphStyle.alignment = NSTextAlignment.left // 居左
let messageText = NSMutableAttributedString(
    string: tipsMessage,
    attributes: [
        NSParagraphStyleAttributeName: paragraphStyle,
        NSFontAttributeName : UIFont.systemFont(ofSize: 14), // 设置一下字号
        NSForegroundColorAttributeName : COLOR_F
    ]
)
myAlert.setValue(messageText, forKey: "attributedMessage") // 通过KVC 进行修改
self.present(myAlert, animated: true, completion: nil)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 天空阴沉昏暗 ,零星小雨时断时续,远处山峦起伏 ,迷雾笼罩。 车子沿着蜿蜒曲折的山路 ,匍匐而上。几...
    官小姐不当官阅读 378评论 0 2
  • 像没有思想的行尸走肉 独自坠入凡尘俗网 心中的莫名无与诉说 浮华乱世亦无所追求 灵魂空虚的惶恐 耐不住黑夜的撕扯 ...
    小九轩阿怪阅读 109评论 0 1
  • 一篇文章的标题,就像男女相亲时见到的第一眼;有没有兴趣继续了解下去,就看第一眼是否吸引人了。 六子老师总结了标题吸...
    无花岛主夫人阅读 469评论 3 5
  • 孤独使人强大也使其脆弱———浅谈《闻香识女人》中校角色 第一次看到电影名的时候直接感官是一部高雅文艺的爱情片,...
    晓曦12阅读 318评论 0 0