Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

cocoa touch - UITextField in UIAlertView on iPhone - how to make it responsive?

I placed a UITextField into a UIAlertView and moved it up so the keyboard wouldn't cover it up with the following code:

[dialog setDelegate:self];
[dialog setTitle:@"Enter Name"];
[dialog addButtonWithTitle:@"Cancel"];
[dialog addButtonWithTitle:@"OK"];
UITextField * nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[nameField setBackgroundColor:[UIColor whiteColor]];
[dialog addSubview:nameField];
CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 100.0);
[dialog setTransform: moveUp];
[dialog show];

I also have the following code to deal with the alert view:

- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{    
    NSLog(@"%d", (int) buttonIndex);
    if (buttonIndex == 1) { // OK pushed
        NSLog([alert textField].text); // does not log anything
    } else {
        // Cancel pushed
}}

I also have a UIAlertViewExtended.h file that contains:

@class UITextField, UILabel;

@interface UIAlertView(Extended)

-(UITextField *)textField;

@end

My question is how do I get the text the user entered and how do I dismiss the keyboard?

Thanks, Ben

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Anyone supporting iOS 5.0 onwards with ARC, there's this direct alertViewStyle property you can set:

-(void)showAlertWithTextField{
    UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:@"Enter Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil];    
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];

    // Change keyboard type
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1)
        NSLog(@"%@",[[alertView textFieldAtIndex:0]text]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...