以编程方式向UIToolBar添加按钮

时间:2015-10-07 12:03:53

标签: ios objective-c

我添加了一个工具栏,然后以编程方式添加了3个按钮。然而,3个按钮都混乱到一个角落。我想要做的是在3个按钮之间有均匀的空间,这样UI看起来不错。

我该怎么做?

UIButton *button = [UIButton buttonWithType:100];

[button addTarget:self action:@selector(hideGender:) forControlEvents:UIControlEventTouchUpInside];

[button setImage:[UIImage imageNamed:@"img"] forState:UIControlStateNormal];

[button setTitle:@"Images" forState:UIControlStateNormal];

button.imageEdgeInsets= UIEdgeInsetsMake(0.0, 0.0, 0, 50);

button.tag=0;


UIButton *button2 = [UIButton buttonWithType:100];

[button2 addTarget:self action:@selector(hideSchool:) forControlEvents:UIControlEventTouchUpInside];

button2.tag=2;

button2.imageEdgeInsets= UIEdgeInsetsMake(0.0, 0.0, 0, 50);

[button2 setImage:[UIImage imageNamed:@"img22"] forState:UIControlStateNormal];



UIButton *button3 = [UIButton buttonWithType:100];

[button3 addTarget:self action:@selector(hideCar:) forControlEvents:UIControlEventTouchUpInside];

button.tag=3;

button3.imageEdgeInsets= UIEdgeInsetsMake(0.0, 0.0, 0,50);

[button3 setImage:[UIImage imageNamed:@"img3"] forState:UIControlStateNormal];



UIBarButtonItem *barButtonItem0 = [[UIBarButtonItem alloc] initWithCustomView:button] ;

UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:button2] ;

UIBarButtonItem *barButtonItem3 = [[UIBarButtonItem alloc] initWithCustomView:button3] ;

更新:我想只使用UI按钮

1 个答案:

答案 0 :(得分:0)

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBackButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
[toolBar setItems:[NSArray arrayWithObject:barBackButton]];

现在在setItems设置按钮数组。假设你想要放三个按钮,那么每个按钮的宽度将是screenWidth / 3,文本将是居中对齐的。通过这种方式,按钮没有超载。