ios - 如何将 UILabel 添加为 UIButton iOS 的 subview

标签 ios uibutton uilabel subview

我想在 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 Class Reference 中所述,您应该使用 setTitle:forState: 设置标题。

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

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

希望这对您有所帮助!

关于ios - 如何将 UILabel 添加为 UIButton iOS 的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12667390/

相关文章:

uiview - Core-plot、UIView 和 UILable 导致文本颠倒

ios - 如何判断UIViewController是第一次启动?

iphone - UIWebView 到 View Controller ?

ios - UIImageView 上的手势识别器(滑动)

ios - 为什么在从另一个页面传递值之前,UILable 不会显示?

iphone - 超越 UIView 的交互

ios - iOS获取要在UIButton中设置的默认UISearchBar图标

ios - 将 UILabel 高度调整为文本

ios - 将值从一个ViewController传递给Objective-C中的另一个

iOS:rootController 中的方法不会被调用