Uitextfield in Uialertcontroller (Border, Backgroundcolor)

UITextField in UIAlertController (border, backgroundColor)

Had some fun with this. The following seems to work. Obviously judging by what was required, it has no future proofing and is a patch away from not working.

I figured this out by walking the view hierarchy in the debugger, from which I noticed a UIVisualEffectView. Removing that seems to give you what you want along with setting the containing view to a clear background. Without removing the visual effect, a clear background shows what is behind the alert view itself for some reason.

UIAlertController *alertController = 
[UIAlertController alertControllerWithTitle:@"Its Not Pretty!"
message:@"Some times things get ugly!"
preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
textField.text = @"Text: No border and clear 8^)";

}];
[self presentViewController:alertController animated:TRUE completion:^{
}];

for (UIView* textfield in alertController.textfields) {
UIView *container = textField.superview;
UIView *effectView = container.superview.subviews[0];

if (effectView && [effectView class] == [UIVisualEffectView class]){
container.backgroundColor = [UIColor clearColor];
[effectView removeFromSuperview];
}
}

Changing UIAlertController textfield's background color doesn't work

The border & background style isn't decided by UITextField actually if you debug it by view hierarchy as Figure 1.

View hierarchy

You do this change:

extension UITextField {

func useUnderLine() {

....

superview?.backgroundColor = .clear

let view = superview?.superview
view?.subviews.first?.alpha = 0
view?.backgroundColor = .clear

}

}

Modify the presending function too:

    present(alert, animated: false, completion: {
if let textField = alert.textFields?.first {
textField.useUnderLine()
}
})

Screenshot

But aware that the View hierarchy might be different of different iOS version in the future.

How do I make my textField border change to a different color every-time it is selected?

In your UITextField subclass, you can override becomeFirstResponder and resignFirstResponder and perform your changes there:

class YourTextFieldSubclass: UITextField {
override func becomeFirstResponder() -> Bool {
let didBecomeFirstResponder = super.becomeFirstResponder()

if didBecomeFirstResponder {
layer.borderColor = UIColor.red.cgColor
layer.borderWidth = 2
layer.cornerRadius = 5
}

return didBecomeFirstResponder
}

override func resignFirstResponder() -> Bool {
let didResignFirstResponder = super.resignFirstResponder()

if didResignFirstResponder {
layer.borderColor = UIColor.clear.cgColor
layer.borderWidth = 0
layer.cornerRadius = 0
}

return didResignFirstResponder
}
}

Make sure to call super and return that value for both of these overridden methods as in the above example.



Related Topics



Leave a reply



Submit