我对iOS
和xcode很新。我想在不使用nib文件或故事板的情况下创建文本字段。我搜索了答案,但到处都是令人困惑的,或者他们使用了nib文件。我已经创建了按钮,它的工作正常,但对于遇到问题的文本字段。这是我的viewcontroller.m
请帮助。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)loadView {
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor purpleColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UITextField *textfield;
button.frame = CGRectMake(10 ,350 , 300, 40);
button1.frame = CGRectMake(10 ,50 , 300, 40);
textfield.frame = CGRectMake(10, 100, 200, 30);
[button setTitle:@"Change screen to green!" forState:UIControlStateNormal];
[button1 setTitle:@"click screen to red!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[button1 addTarget:self action:@selector(buttonPressed1) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[self.view addSubview:button1];
[self.view addSubview:textfield];
}
-(void)buttonPressed {
self.view.backgroundColor = [UIColor greenColor];
}
-(void)buttonPressed1 {
self.view.backgroundColor = [UIColor redColor];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
谢谢&问候
答案 0 :(得分:1)
您刚刚宣布了UITextField
而不是分配。您必须先分配它,然后设置frame
&将其添加到view
上 -
UITextField *txt = [[UITextField alloc] init];
txt.frame = CGRectMake(10, 100, 200, 30);
txt.delegate = self;
[self.view adsubview:txt];
它解决了你的问题。
答案 1 :(得分:1)
首次使用
UITextField *textfield = [[UITextField alloc] init];
而不是
UITextField *textfield;
然后设置textfield的背景颜色,因为默认情况下背景颜色将为clearColor。
textfield.backgroundColor = [UIColor whiteColor];
或使用
textfield.borderStyle = UITextBorderStyleRoundedRect;
获得带白色边框的文本字段。
答案 2 :(得分:0)
使用此:
UITextField *textfield = [[UITextField alloc] init];
而不是
UITextField *textfield;
UITextField *textfield;
只需创建对象引用Not object。
答案 3 :(得分:0)
如果您已按照建议的答案添加了alloc init,则您的文本字段实际上在屏幕上,但由于它没有边框或没有文本,因此您无法看到它。尝试添加此行,然后您将看到它:
textfield.borderStyle = UITextBorderStyleRoundedRect;
答案 4 :(得分:0)
UITextField *textfield =[[UITextField alloc] init];
textfield.frame = CGRectMake(10, 100, 200, 30);
textfield.delegate = self; [self.view addSubview:textfield];
[self.view bringSubViewToFront:textfield];
可以解决问题