0

我知道我可以这样做:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(x, y, width, height);
    [button setTitle:text forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor clearColor];

但这会在按钮周围留下一个边框。

我也可以这样做:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(x, y, width, height);
    [button setTitle:text forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

然后在按钮后面放一个 UILabel 。

有没有办法在不需要两个对象的情况下完成这个 ^ ?

更新:澄清我的问题:我想要有文本,只有文本,按下时执行方法调用。出于难以解释的原因,我需要通过按钮来执行此操作。那么,如何使按钮的文本成为按钮的唯一可见部分。无边界。没有背景。只是文字。

4

4 回答 4

4
    UIButton *btnLikeUserCount = [[[UIButton alloc] init] autorelease];
    [btnLikeUserCount.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
    btnLikeUserCount.frame = CGRectMake(posx,posy,width,height);
    [btnLikeUserCount setTitle:text forState:UIControlStateNormal];
    [btnLikeUserCount setTitleColor:[UIColor colorWithRed:50/255.0 green:79/255.0 blue:133/255.0 alpha:1.0] forState:UIControlStateNormal];
    [btnLikeUserCount addTarget:self action:@selector(btnLikeUserCountClick:) forControlEvents:UIControlEventTouchUpInside];

无需带标签对象。

于 2013-03-28T05:57:53.993 回答
2

我无法准确获得您想要的东西,但您[self.view addSubview:button]的代码中可能会遗漏您的信息。所以你不能显示带有文本的按钮

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(x, y, width, height);
    [button setTitle:text forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
于 2013-03-28T06:03:27.040 回答
0

您的第二个代码工作正常。在下图中,hello 是一个按钮。 在此处输入图像描述

我的代码是:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(110, 100, 100, 50);
[button setTitle:@"Hello" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
于 2013-03-28T06:03:55.087 回答
0

这样你就可以做到这一点

 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
 button.frame = CGRectMake(100, 400, 100, 50);
 [button setTitle:@"Button text" forState:UIControlStateNormal];
 [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
 [button.layer setBorderColor: [UIColor clearColor]];
 [button.layer setBorderWidth: 0.0];
 [self.view addSubview:button];
于 2013-03-28T06:41:30.433 回答