I crea开发者_Python百科te a uialertview with two button and a textfield, and I want a disable the button "Ok" if the textfield is empty. How I can get the uibutton object, to change is enabled status.
You can use the enabled
property inherited from UIControl
:
for(UIView *view in alertView.subviews) {
if([view isKindOfClass:[UIButton class]]) {
((UIButton *) view).enabled = NO;
}
}
For the sake of reusability, this becomes even simpler when you have a category on NSArray
which retrieves objects of a given class:
@implementation NSArray (JRAdditions)
- (NSArray *)objectsOfClass:(Class)cls {
NSParameterAssert(cls);
NSMutableArray *array = [@[] mutableCopy];
for(id obj in self) if([obj isKindOfClass:cls]) [array addObject:obj];
return [array copy];
}
@end
Your code can now look like this:
[[alertView.subviews objectsOfClass:[UIButton class]] enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger index, BOOL *stop) {
obj.enabled = NO;
}];
Since iOS 5, you can do this in the UIAlertViewDelegate instance.
-(BOOL) alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
return [[alertView textFieldAtIndex:0].text length] > 0;
}
精彩评论