如何将UILabel添加为UIButton iOS的子视图



我想在UIButton中添加一个UILabel。这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[self addressSearch] setDelegate:self];
    [[self worldMap] setDelegate:self];
    self.boolPushButtonTapped = YES;
    self.addressSearch.barStyle = 1;
    //Create pushButton
    self.pushButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.pushButton.frame = CGRectMake(106, 436, 110, 59);
    [self.pushButton setBackgroundImage:[UIImage imageNamed:@"pushButton2.png"] forState:UIControlStateNormal];
    [self.pushButton addTarget:self action:@selector(pushButtonTapped) forControlEvents:UIControlEventTouchUpInside];

    //Label
    self.distanceLabel = [[UILabel alloc] init];
    self.distanceLabel.text = @"test";
    [self.pushButton addSubview:self.distanceLabel];

    [self.view addSubview:self.pushButton];
}

如果我不使用alloc init则会收到错误,如果我使用该标签中的文本不会更改。错误:

*** Assertion failure in -[NSLayoutConstraint constant], /SourceCache/Foundation/Foundation-992/Layout.subproj/NSLayoutConstraint.m:560
2012-10-01 14:01:01.889 RemindMe[1116:907] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '(null)'

我想在这个按钮中添加,因为有一个动画。

有什么建议吗?

你可以试试这个:

[self.pushButton.titleLabel setText: @"anytext"];

更新的答案:

如 UIButton 类参考中所述,应使用 setTitle:forState: 设置标题。

然后,可以在按钮的关联标签对象titleLabel中完成格式化。

因此,您无需添加另一个UILabel。

希望这有帮助!

UIButtons现在给你很多控制,但是在自定义字体等一些东西成为可能之前,我只是做了一个简单的控件,有一个UIButton和UILabel。我只是把UILabel放在UIButton的顶部,用一个小的2px左右的填充。

最新更新