【问题标题】:how to add a textfield by pressing a button如何通过按下按钮添加文本字段
【发布时间】:2013-04-15 03:29:40
【问题描述】:

我试图弄清楚如何通过单击按钮在我的 iphone 应用程序的视图中添加文本字段。有可能吗?

我认为应该就这么简单。但它不起作用。

- (IBAction)addText:(id)sender

CGRect textField = CGRectMake(0.0, 0.0, 100.0, 30.0);
UITextField *textField = [[UITextField alloc] initWithFrame:textField];

【问题讨论】:

  • 当然有可能!让视图来来去去是 iOS 的精髓。你有没有尝试过任何东西?
  • 我改变了我的问题并在那里发布了我的尝试
  • 发布您的真实代码。您发布的内容甚至不接近可以编译的内容。
  • 顺便说一句 - 请比说“它不起作用”要清楚得多。提问时切勿使用这些词。请明确点。它编译吗?如果没有,错误是什么?如果它编译,那么在运行时实际发生了什么?它会崩溃吗?如果是这样,错误是什么,它在哪一行崩溃?如果它没有崩溃,请清楚与应该发生的情况相比会发生什么。正是这些细节决定了问题的好坏。
  • maddy,感谢您的意见。下次需要帮助时我会记住这一点

标签: ios button uiview uitextfield add


【解决方案1】:

嗨,约翰,是的,您可以在单击按钮后创建 uitextfield,您必须编写如下代码

- (IBAction)addText:(id)sender
{
CGRect textfieldFrame = CGRectMake(0.0, 0.0, 100.0, 30.0);
UITextField *textField = [[UITextField alloc] initWithFrame:textfieldFrame];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = @"enter text";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;    
textField.delegate = self;
[self.view addSubview:textField];



}

【讨论】:

  • 这看起来应该可以工作,但事实并非如此。除了这个,还有其他的吗?
  • 嗨,约翰,我编辑了我的答案,请使用此代码,它将有效地工作。
  • 谢谢!!!关心解释问题是什么,以便我可以从中学到一些东西? :)
  • 嗨,John,这里的问题是以前我们为 CGrect 和 UItextfield 使用了相同的对象名称,因为编译器变得混乱并显示错误。现在我将 CGrect 对象名称更改为 textfieldFrame 而不是 textField(我们之前使用的)。这只是主要原因。
  • 非常感谢您的宝贵时间 :)
【解决方案2】:

如果此代码不起作用,则意味着您的 UIButton 的 IBAction 不起作用将 NSLog 放入 IBAction 或写入 UITextView 全局变量,因为它可能是超级调用 dealloc 您的 UITextView。或者,您的 CGRectMake(0.0, 0.0, 100.0, 30.0) 框架超出您的视野可能超过 max with or max height 而您看不到它。

- (IBAction)addText:(id)sender {
     CGRect textFieldFrame = CGRectMake(0.0, 0.0, 100.0, 30.0);
     UITextField *textField = [[UITextField alloc] initWithFrame:textFieldFrame];   
     textField.delegate = self;
     [self.view addSubview:textField];
     // or add to you wanted view
    [yourView addSubview:textField];
}

【讨论】:

  • 不工作,我应该做些什么来让它工作吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
相关资源
最近更新 更多