【问题标题】:Is it possible to adjust x,y position for titleLabel of UIButton?是否可以调整 UIButton 的 titleLabel 的 x,y 位置?
【发布时间】:2011-02-17 23:33:26
【问题描述】:

是否可以调整 titleLabel 的 x,y 位置 UIButton

这是我的代码:

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [btn setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
    [btn setTitle:[NSString stringWithFormat:@"Button %d", i+1] forState:UIControlStateNormal];     
    [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.frame = ???

【问题讨论】:

标签: ios iphone uibutton textlabel


【解决方案1】:
//make the buttons content appear in the top-left
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];

//move text 10 pixels down and right
[button setTitleEdgeInsets:UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 0.0f)];

在 Swift 中

//make the buttons content appear in the top-left
button.contentHorizontalAlignment = .Left
button.contentVerticalAlignment = .Top

//move text 10 pixels down and right
button.titleEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 0.0, 0.0)

斯威夫特 5

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.titleEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 0.0, right: 0.0)

【讨论】:

  • 我什至不需要前两行...setTitleEdgeInsets: 是我发现移动文本所必需的。
  • 这绝对是正确的,但使用界面生成器可能更容易完成(如我的回答中所述)。
  • 前两行将您的文本定位到 0,0 (x,y)。这样可以防止相对定位;特别是如果您在 xib 中设置默认对齐方式。
  • 我从 Web 服务中分配按钮标题并为按钮分配背景图像。有时网络服务值会超过 10 个字母。在这种情况下,它显示点线。我需要如果网络服务值在增加按钮图像也想增加...怎么办?
  • @ArtOfWarfare :如果您的按钮高度更高并且您需要对齐为 ltr... 对于普通按钮,是的,它们没用...
【解决方案2】:

最简单的方法视觉上是使用属性检查器**(在编辑 xib/storyboard 时出现),设置将“edge”属性设置为标题,调整其插图,然后将“edge”属性设置为图像,并进行相应调整。 它通常比编码要好,因为它更易于维护且高度可视化。

【讨论】:

  • Edge 更改为Title 然后调整插图的好提示!
  • 供将来参考,从 Xcode 8 开始,您可以在 Size Inspector 中调整标题插图,而不是设置 edge 属性。
【解决方案3】:

从 UIButton 派生并实现以下方法:

- (CGRect)titleRectForContentRect:(CGRect)contentRect;

编辑:

@interface PositionTitleButton : UIButton
@property (nonatomic) CGPoint titleOrigin;
@end

@implementation PositionTextButton
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
  contentRect.origin = titleOrigin;
  return contentRect;
}
@end

【讨论】:

  • 谢谢,这是我真正需要的。自动居中是不够的。
【解决方案4】:

对于我的项目,我有这个扩展实用程序:

extension UIButton {

    func moveTitle(horizontal hOffset: CGFloat, vertical vOffset: CGFloat) {
        self.titleEdgeInsets.left += hOffset
        self.titleEdgeInsets.top += vOffset
    }

}

【讨论】:

    【解决方案5】:

    这可以在 xib 中完成。选择您的按钮,转到“显示尺寸检查器”选项卡并设置插图。

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2014-09-25
      • 2022-01-01
      • 2018-04-02
      相关资源
      最近更新 更多