ios - 将 UILabel 定位在 UIButton 的文本结尾之后?

标签 ios objective-c uibutton uilabel cgrect

我有一个 View ,它在最左边有一个标签,然后是一个带有用户名的按钮,然后是他在右边按钮之后的评论。我想要做的是将 Label 放置在 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];

最佳答案

如果您想让按钮比标签宽,或者如果您更改按钮上的众多尺寸属性之一,则 sizeToFit 效果不佳。更好的解决方案是简单地将 titleLabel 的坐标系转换为按钮 super View 。

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;

第二行是这里的关键。您要求按钮将其中的矩形(在本例中为标题标签)转换为另一个 View 中的矩形(在本例中为按钮 super View ,这可能是您的 View Controller self.view)。

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

关于ios - 将 UILabel 定位在 UIButton 的文本结尾之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841668/

相关文章:

objective-c - componentsSeparatedByString内存泄漏,能帮我吗?

objective-c - Cocoa 应用程序 - XCode 8 和 App Delegate

Swift - 自动在刚刚添加的按钮右侧添加一个按钮

xcode - iOS将已编译的捆绑软件添加到模拟器

ios - 在 Travis CI 上,iOS 应用程序代码如何签名并上传到 Apple TestFlight?

ios - Xamarin.iOS statusBar BackgroundColor不会更改

ios - App Transport Security 已阻止明文 HTTP 资源

ios - RestKit - 从 RKRequestDescriptor 中排除具有 nil 值的属性映射

iOS:如何在矩形内创建按钮?

推送转换后 iOS 按钮未完全呈现