3

我想在我的视图中添加一个无边框的 UIButton。使用界面生成器,我通过从对象库中拖动一个圆形矩形按钮来完成此操作。然后,在属性检查器上,将类型更改为自定义并将标题保留为“按钮”。界面生成器一切正常。但是,程序化方法并非如此。以编程方式,这就是我的做法:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button setTitle:@"Button" forState:UIControlStateNormal];

当我运行该应用程序时,该按钮不显示。也许我在这里遗漏了一些东西,但是当我将类型更改UIButtonTypeRoundRect为显示按钮时。但是,我希望按钮是无边框的。

无论如何,我总是可以使用界面生成器。但是,我想了解为什么程序化方法不起作用。那么,有谁知道问题出在哪里?

4

3 回答 3

7

UIButtonTypeCustom真的,实际上是一种自定义按钮类型。默认情况下没有为它设置有意义的值。如果要显示它,则必须将其背景颜色和/或其标题颜色设置为不透明的:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button setTitle:@"Button" forState:UIControlStateNormal];
// Set visible values
[button setBackgroundColor:[UIColor greenColor]];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[someSuperview addSubview:button];
于 2012-11-13T17:21:14.133 回答
3

在这里,我使用了您的代码,您缺少的是

 [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
于 2012-11-13T17:21:38.037 回答
1

Hi I was in the same situation. I do not know why somewhere in my code there was

button.translatesAutoresizingMaskIntoConstraints = NO;

Once I've deleted that line I was able to set my button frame without any issues. Hope this helps

于 2014-10-08T10:06:37.907 回答