iOS:如何从文本字段中获取文本并将其显示在警报中?

mrc*_*son 4 objective-c uitextfield uialertview ios

家伙.这听起来好像我要求你为我做功课,但我不是.我的雇主终于给了我这款甜美的全新MacBook Pro.我的任务之一将包括一些iOS开发.我对此很感兴趣,我正试图潜入学习,所以我正在制作一个愚蠢的小应用程序,让我看看如何交互和编写一些代码.今天早上的任务是从文本字段中获取一些文本并将其显示在警报中.我已经做了大量的谷歌搜索并发现了很多东西 - 甚至是StackOverflow上的东西 - 但是很多东西都在我脑海中或与之不完全相关.所以,我希望有人可以告诉我我做错了什么.

这是我的文本字段代码:

-(IBAction)showInputMessage:(UITextField *)textField
{
if ([textField.text isEqualToString:@""])
{
    return;
}
UIAlertView *helloEarthInputAlert = [[UIAlertView alloc]
                                     initWithTitle:@"Name!" message:[NSString stringWithFormat:@"Message: %@", textField.text]
                                     delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
// Display this message.
[helloEarthInputAlert show];

}
Run Code Online (Sandbox Code Playgroud)

然后我将该文本字段连接到showInputMessage并在iPhone模拟器中运行它,但是当我输入文本并单击"Enter"时没有任何反应.

提前致谢.我从昨晚开始只玩这种语言.

杰里米

Abd*_*que 6

为UITextView设置委托.

首先声明代表:

@interface YourViewController ()<UITextFieldDelegate>
Run Code Online (Sandbox Code Playgroud)

第二集自我

self.textView.delegate = self;
Run Code Online (Sandbox Code Playgroud)

使用此方法:

-(void)textViewShouldReturn:(UITextField *)textField
{
   if ([textField.text isEqualToString:@""]){
         return;
    }      

    UIAlertView *helloEarthInputAlert = [[UIAlertView alloc]
                           initWithTitle:@"Name!" message:[NSString stringWithFormat:@"Message: %@", textField.text]
                           delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
 // Display this message.
 [helloEarthInputAlert show];

}
Run Code Online (Sandbox Code Playgroud)

要添加属性,请在h文件中写入以下代码:

 @property (weak, nonatomic) IBOutlet UITextView *textView;
Run Code Online (Sandbox Code Playgroud)

要连接它,您的文本字段将转到故事板并单击其视图控制器.接下来转到Connections Inspector(右边一直).在出口下方拖动textView旁边的圆圈到textView.