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

时间:2012-10-01 04:02:00

标签: ios uibutton uilabel subview

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

- (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)'

我想在此按钮内添加,因为有动画。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

你可以试试这个:

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

更新回答:

正如UIButton Class Reference中所述,您应该使用setTitle:forState:设置标题。

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

所以你不需要添加另一个UILabel。

希望这有帮助!