我已经以编程方式将按钮添加到我的视图中,但是当我在模拟器上测试时,只有工具栏在视图上可见。
我做错了什么?
我在头文件中定义了我的ui元素,并在主文件中合成,然后在viewDidLoad方法中初始化。 但是有些不对劲。
我的代码如下;
#import "ViewController.h"
@implementation ViewController
@synthesize iAmLost, iAmLooking, about, howToUse,appsFromKodAtolye, exit;
- (void)viewDidLoad
{
[super viewDidLoad];
toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, 320.0, 40.0)];
iAmLost = [[UIButton alloc]initWithFrame:CGRectMake(0,0, 200.0, 10.0)];
iAmLooking = [[UIButton alloc ]initWithFrame:CGRectMake(0, 0, 200.0, 10.0) ];
[iAmLooking addTarget:self
action:@selector(iAmLookingScreen)
forControlEvents:UIControlEventTouchUpInside];
about = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200.0, 10.0)];
howToUse = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200.0, 10.0)];
exit = [[UIBarButtonItem alloc] initWithTitle:@"Exit" style:UIBarButtonItemStyleBordered target:self action:@selector(exitApp:)];
NSArray *buttons = [[NSArray alloc]
initWithObjects:exit, nil];
toolbar.items = buttons;
[self.view addSubview:iAmLost];
[self.view addSubview:iAmLooking];
[self.view addSubview:about];
[self.view addSubview:toolbar];
}
答案 0 :(得分:3)
您将按钮放在工具栏下方,将每个项目添加到0,0。由于工具栏是您添加到子视图的最后一项,它将显示在所有按钮的顶部,因此您将无法看到按钮。
框架由4个x坐标,y坐标,高度,宽度组成
尝试更改这些
的x和y坐标例如
toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, 320.0, 40.0)];
iAmLost = [[UIButton alloc]initWithFrame:CGRectMake(0,100, 200.0, 10.0)];
iAmLooking = [[UIButton alloc ]initWithFrame:CGRectMake(0, 200, 200.0, 10.0) ];
您还应注意,您目前尚未为按钮或任何标题设置任何样式。可能值得设置标题或背景颜色,以便您可以实际查看屏幕上放置的按钮并告诉哪个按钮。
答案 1 :(得分:2)
由于您将工具栏添加为最后一个子视图,因此所有按钮都位于工具栏下方。 您必须将按钮添加为工具栏的子视图。另请注意,您将所有按钮放在同一位置。
答案 2 :(得分:1)
您有四个按钮和一个工具栏。工具栏的框架完全正确,即
(0, 0, 320.0, 40.0)
但对于按钮,您为所有按钮提供相同的坐标,因此它是重叠的。更好的是你会改变按钮坐标。 如果要在工具栏上添加这些按钮,请正确设置坐标并使用
[toolBar addSubView: button];
答案 3 :(得分:0)
简单,只需检查原点x& y为每个按钮
UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, 320.0, 40.0)];
UIButton *iAmLost = [[UIButton alloc]initWithFrame:CGRectMake(5,50, 200.0, 10.0)];
iAmLost.backgroundColor = [UIColor redColor];
UIButton * iAmLooking = [[UIButton alloc ]initWithFrame:CGRectMake(0, 70, 200.0, 10.0) ];
[iAmLooking addTarget:self
action:@selector(iAmLookingScreen)
forControlEvents:UIControlEventTouchUpInside];
UIButton * about = [[UIButton alloc]initWithFrame:CGRectMake(0, 90, 200.0, 10.0)];
about.backgroundColor = [UIColor greenColor];
UIButton * howToUse = [[UIButton alloc]initWithFrame:CGRectMake(0, 120, 200.0, 10.0)];
howToUse.backgroundColor = [UIColor blackColor];
UIBarButtonItem* exit = [[UIBarButtonItem alloc] initWithTitle:@"Exit" style:UIBarButtonItemStyleBordered target:self action:@selector(exitApp:)];
NSArray *buttons = [[NSArray alloc]
initWithObjects:exit, nil];
toolbar.items = buttons;
[self.view addSubview:iAmLost];
[self.view addSubview:iAmLooking];
[self.view addSubview:howToUse];
[self.view addSubview:about];
[self.view addSubview:toolbar];