我正在尝试使用操作表样式创建 UIAlertController,但我想将背景颜色更改为灰色。我已经能够找到一种方法来更改 UIAlertController 的背景颜色,但不能更改取消按钮。单独的取消按钮保持白色。
这是我现在拥有的代码:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:@"Option 1" style:UIAlertActionStyleDefault handler:nil]];
[alert addAction:[UIAlertAction actionWithTitle:@"Option 2" style:UIAlertActionStyleDefault handler:nil]];
[alert addAction:[UIAlertAction actionWithTitle:@"Option 3" style:UIAlertActionStyleDefault handler:nil]];
[alert addAction:[UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:nil]];
[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
UIView *firstSubview = alert.view.subviews.firstObject;
UIView *alertContentView = firstSubview.subviews.firstObject;
for (UIView *subSubView in alertContentView.subviews) {
subSubView.backgroundColor = [UIColor darkGrayColor]; // Here you change background
}
alert.view.tintColor = [UIColor whiteColor];
[self.controller presentViewController:alert animated:YES completion:nil];
这给了我以下结果:
Link
我访问过How to change the background color of the UIAlertController? 但没有一个解决方案有自定义的取消按钮背景颜色。
任何帮助,将不胜感激!
最佳答案
有一个非常肮脏的解决方案,但它有效。我们将使用 UI外观以此目的。
首先,我们需要为 UIView 准备一个特殊的私有(private)扩展,以便能够更改它的 subview 背景颜色。
fileprivate extension UIView {
private struct AssociatedKey {
static var subviewsBackgroundColor = "subviewsBackgroundColor"
}
@objc dynamic var subviewsBackgroundColor: UIColor? {
get {
return objc_getAssociatedObject(self, &AssociatedKey.subviewsBackgroundColor) as? UIColor
}
set {
objc_setAssociatedObject(self,
&AssociatedKey.subviewsBackgroundColor,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
subviews.forEach { $0.backgroundColor = newValue }
}
}
}
每次我们设置 subiews背景颜色 value UIView 将迭代它的 subview 并为每个 subview 设置一个新的背景颜色。
正如您在下面的答案中看到的,有一个名为 的特殊 UIView _UIAlertControlleriOSActionSheetCancelBackgroundView 在 UIAlertController 的层次结构中,它包含一个白色的 subview (用于取消按钮)
让我们尝试获取它的外观并使用我们的属性来更改它的 subview 颜色。我想这是一种私有(private)的api。
if let cancelBackgroundViewType = NSClassFromString("_UIAlertControlleriOSActionSheetCancelBackgroundView") as? UIView.Type {
cancelBackgroundViewType.appearance().subviewsBackgroundColor = .red
}
将此代码放在 AppDelegate 的 didFinishLaunching 或专用类中。
就是这样。现在您可以在红色背景上看到取消按钮。在 iOS 11 上测试。
关于ios - UIAlertController 更改操作表的取消按钮的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601692/