-1

我对iOSxcode 很陌生。我想在不使用 nib 文件或情节提要的情况下创建一个文本字段。我搜索了答案,但到处都令人困惑,或者他们使用了 nib 文件。我已经创建了按钮并且它工作正常,但是对于文本字段 m 面临问题。这是我的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

感谢和问候

4

5 回答 5

1

您刚刚声明了UITextField而不是分配。您必须先分配它,然后设置frame并添加它view-

UITextField *txt = [[UITextField alloc] init];
txt.frame = CGRectMake(10, 100, 200, 30);
txt.delegate = self;
[self.view adsubview:txt];

它解决了你的问题。

于 2013-01-11T05:15:13.463 回答
1

首次使用

UITextField *textfield = [[UITextField alloc] init];

代替

UITextField *textfield;

然后设置文本字段的背景颜色,因为背景颜色默认为 clearColor。

textfield.backgroundColor   =   [UIColor whiteColor];

或使用

textfield.borderStyle = UITextBorderStyleRoundedRect;

获得白色边框的文本字段。

于 2013-01-11T06:31:46.013 回答
0
UITextField *textfield =[[UITextField alloc] init];
 textfield.frame = CGRectMake(10, 100, 200, 30); 
textfield.delegate = self; [self.view addSubview:textfield];
[self.view bringSubViewToFront:textfield];

可以解决问题

于 2013-01-11T06:49:15.650 回答
0

用这个:

UITextField *textfield = [[UITextField alloc] init];

插图

UITextField *textfield;

UITextField *textfield;只是 crete 对象引用不是对象。

于 2013-01-11T05:12:26.570 回答
0

如果您像答案所建议的那样添加了 alloc init,那么您的文本字段实际上就在屏幕上,但是由于它没有边框或没有文本,所以您看不到它。尝试添加这一行,然后你会看到它:

textfield.borderStyle = UITextBorderStyleRoundedRect;
于 2013-01-11T06:11:54.307 回答