首页 文章

在UIButton文本结束后定位UILabel?

提问于
浏览
0

我有一个视图,在最左边有一个标签,然后是一个带有用户名的按钮,然后是右边按钮后的注释 . 我想要做的是将标签定位在UIButton的文本结尾处 . 在这种情况下,如果用户名是长或短,则注释将在用户名按钮和注释标签之间没有任何空格的情况下开始 . 我目前正在做这样的硬编码,如何根据UIButtion的文本大小实现UILabel的动态位置?,PfButton是UIButton的子类谢谢

PfButton *button = [PfButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:name forState:UIControlStateNormal];
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentEdgeInsets:UIEdgeInsetsMake(0, 13, 0, 0)];
[button setObjectId:objId];
[button addTarget:self action:@selector(profilePhotoButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(30, -7, 130, 20)];
[[button titleLabel] setTextAlignment:NSTextAlignmentLeft];
[view addSubview:button];

UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, -7, 150, 20)];
[messageLabel setFont:[UIFont systemFontOfSize:15]];
[messageLabel setText:msg];
[messageLabel setTextAlignment:NSTextAlignmentLeft];
[view addSubview:messageLabel];
[messageLabel release];

2 回答

  • 0

    如果要使按钮宽于标签,或者更改按钮上的许多大小调整属性之一,sizeToFit将无法正常工作 . 更好的解决方案是简单地将titleLabel的坐标系转换为按钮superview .

    CGRect buttonTitleFrame = button.titleLabel.frame;
    CGRect convertedRect = [button convertRect:button.titleLabel.frame toView:button.superview];
    CGFloat xForLabel = convertedRect.origin.x + buttonTitleFrame.size.width;
    CGRect currentLabelFrame = label.frame;
    CGRect labelFrame = CGRectMake(xForLabel, currentLabelFrame.origin.y, currentLabelFrame.size.width, currentLabelFrame.size.height);
    label.frame = labelFrame;
    

    第二行是关键的一行 . 您要求按钮将其中的矩形(在本例中为 Headers 标签)转换为在另一个视图中的矩形(在这种情况下,按钮superview,可能是您的视图控制器self.view) .

    第3行采用平移原点并添加标签精确宽度,5使用标签框架中除x之外的值,这是我们的计算值 .

  • 1

    通过使用它来工作

    [button sizeToFit];
    

    它给了我确切的框架,然后通过考虑按钮的x位置和宽度来计算标签的位置

相关问题