UITextfield.text到UILabel.text

时间:2014-01-11 14:54:20

标签: ios iphone objective-c xcode ios7

我正在制作的是iPhone应用程序(单一视图(最新XCode)),其按钮带有标签和textfield

我想要做的是,让用户输入一个名称,然后按下按钮并将标签更改为Hello {输入的名称}。

我一直在寻找,而不是任何有用的东西。

label.text = [NSString stringWithFormat:@"%@%@", label.text, textField1.text]; // Didn't work.

我做过,View2.hView2.m。 其中的代码:

View2.h

#import <UIKit/UIKit.h>

@interface View2 : UIViewController
{

IBOutlet UILabel *HelloWorldLabel;
IBOutlet UITextField *NameText;
}

-(IBAction)Button:(id)sender;

@end

View2.m

-(IBAction)Button:(id)sender{

}

EDIT1:

我的故事板

enter image description here

5 个答案:

答案 0 :(得分:2)

HelloWorldLabel.text = [NSString stringWithFormat:@"Hello %@", NameText.text];应该可以正常工作。

答案 1 :(得分:2)

您发布的代码有一个空的IBAction方法。如果这是您的实际代码,那么当然没有任何事情发生。如果这不是您的实际代码,那么发布您的实际代码。我们无法帮你调试我们看不到的东西,而魔鬼就在细节中。

此外,您应该遵循Cocoa命名约定。属性和实例方法名称应以小写标签开头,名称应描述它的作用。

您的 HelloWorldLabel 应为 helloWorldLabel NameText 应为 nameTextField

发布您的整个IBAction方法。还要添加日志语句以确保您的插座正确链接:

-(IBAction)Button:(id)sender
{
  NSLog(@"helloWorldLabel field = %@. nameTextField = %@", helloWorldLabel, nameTextField);
  self.helloWorldLabelText.text = [NSString stringWithFormat:@"Hello, %@", nameTextField.text];
}

运行程序时,单击按钮时查看日志输出。如果您没有看到任何内容,则IBAction未与该按钮相关联。如果日志语句显示NULLnameTextField helloWorldLabel,则说明这些商店未正确连接。

答案 2 :(得分:0)

试试这个:

-(IBAction)Button:(id)sender{
   self.helloWorldLabelText.text = [NSString stringWithFormat:@"Your text here"];
}

答案 3 :(得分:0)

只需将其添加到按钮事件

即可
   NSString *str = nameText.text;
   HelloWorldLabel.text = [NSString stringWithFormat:@"%@%@", @"Hello",str];

答案 4 :(得分:0)

你可以这样做:

- (BOOL)textFieldShouldReturn:(UITextField *)yourTextField {
    //when the user taps "return" on the keyboard of "yourTextField" it will update the label
    [self updateLabel];
    return NO;
}

- (void) updateLabel{
    //change your Label, "myLabel" to the text from "yourTextField"
    myLabel.text = [NSString stringWithFormat:@"%@", yourTextField.text];
}

另外,如果您想在用户按下return键时让键盘消失,只需将以下代码添加到textFieldShouldReturn:方法中:

[yourTextField resignFirstResponder];

如果您想在用户按下按钮而不是textFieldShouldReturn:方法时执行此操作,则可以使用:

- (IBAction) buttonPressed{
    [self updateLabel];
}

只需确保在按下按钮时指定buttonPressed操作!

此外,请确保同时声明操作buttonPressed(如果您使用它)和您的UILabel myLabel

相关问题