我知道我可以这样做:
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放在按钮后面。
有没有办法完成这个^而不需要两个对象?
更新: 澄清我的问题: 我想要有文本,只有文本,按下时执行方法调用。由于解释复杂的原因,我需要通过按钮来完成此操作。那么,如何使按钮文本成为按钮的唯一可见部分。无边界。没有背景。只是发短信。
答案 0 :(得分: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];
无需使用标签对象。
答案 1 :(得分: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];
答案 2 :(得分:0)
你的第二个代码工作正常。在下图中,你好是一个按钮。
我的代码是:
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];
答案 3 :(得分: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];