如何修改特定操作表样式UIAlertController的字体颜色?
修改UIAlertAction字体颜色为绿色的实现方案
嘿,要把操作表(Action Sheet)里的所有操作项字体改成绿色其实很简单,你只需要给每个UIAlertAction添加富文本属性就行。我在你提供的代码基础上做了完善,直接就能用:
func showAlertSheet() { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // 定义绿色文本的富文本属性 let greenTextAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.green ] let accountAction = UIAlertAction(title: "Account", style: .default) { (action) in self.performSegue(withIdentifier: "toAccountVC", sender: nil) } // 给Account按钮设置绿色字体 accountAction.setValue(NSAttributedString(string: "Account", attributes: greenTextAttributes), forKey: "attributedTitle") let logoutAction = UIAlertAction(title: "Logout", style: .default) { (action) in // 这里可以添加Logout的逻辑 } // 给Logout按钮设置绿色字体 logoutAction.setValue(NSAttributedString(string: "Logout", attributes: greenTextAttributes), forKey: "attributedTitle") let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in // 取消按钮的逻辑 } // 给Cancel按钮设置绿色字体(如果需要的话,也可以保留默认颜色) cancelAction.setValue(NSAttributedString(string: "Cancel", attributes: greenTextAttributes), forKey: "attributedTitle") // 将所有操作项添加到操作表 actionSheet.addAction(accountAction) actionSheet.addAction(logoutAction) actionSheet.addAction(cancelAction) // 弹出操作表 present(actionSheet, animated: true, completion: nil) }
关键说明:
- 我们先创建了一个包含
foregroundColor(字体颜色)的属性字典,指定为绿色。 - 通过
setValue(_:forKey:)方法给每个UIAlertAction设置attributedTitle(富文本标题),这是兼容iOS旧版本的通用写法。 - 如果你使用的是iOS 15及以上版本,可以用更简洁的方式直接初始化带富文本的操作项,示例如下:
let accountAction = UIAlertAction( attributedTitle: NSAttributedString(string: "Account", attributes: greenTextAttributes), style: .default ) { action in self.performSegue(withIdentifier: "toAccountVC", sender: nil) }
这样修改后,操作表里的所有按钮字体就会变成你想要的绿色啦!
内容的提问来源于stack exchange,提问作者Agung
相关产品推荐
相关产品推荐

