【问题标题】:Text is not center Aligned in Rounded UI Button - ObjectiveC圆形UIButton中的文本未居中对齐-Objective C
【发布时间】:2016-10-26 07:22:33
【问题描述】:

我使用以下代码制作了一个浮动图标。

- (void)createFloatingButton
{

UIButton *floatingButton = [UIButton buttonWithType:UIButtonTypeCustom];
floatingButton.frame = CGRectMake(kScreenWidth-kFloatingButtonSize-kFloatingButtonSize/2, self.view.frame.size.height-kFloatingButtonSize-kFloatingButtonSize/2, kFloatingButtonSize,kFloatingButtonSize);
[floatingButton setBackgroundColor:kNavColor];
floatingButton.layer.cornerRadius = kFloatingButtonSize/2;

//Configre Font and Text
[floatingButton setTitle:@"+" forState:UIControlStateNormal];
floatingButton.titleLabel.font = [UIFont systemFontOfSize:30];

[floatingButton addTarget:self action:@selector(floatingButtonTapped) forControlEvents:UIControlEventTouchUpInside];

//Mange Alignment
floatingButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
floatingButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

//Add shadow
floatingButton.layer.shadowColor = [[UIColor blackColor] CGColor];
floatingButton.layer.shadowOffset = CGSizeMake(0, 2.0f);
floatingButton.layer.shadowOpacity = 0.6f;
floatingButton.layer.shadowRadius = 3.0f;
floatingButton.layer.masksToBounds = NO;

[self.view addSubview:floatingButton];
}

我的输出是这样的:

我无法将+ 置于中心位置。

【问题讨论】:

  • 您可以使用带 + 的图像来代替所有这些操作。用 + 本身制作一张图像。对于 + 来说,这很容易没有问题
  • @Jecky In Image 我必须添加点击手势,或者如果我将 UIImage 放在 UIButton 后面,代码会增加,我不想使用 Imgaege。
  • "floatingButton.titleLabel.textAlignment = NSTextAlignmentCenter;"应该很有用。
  • @alicanbatur 不工作
  • 如果你必须使用 + 作为字符串,你应该改变字体大小以获得最佳外观。如果您不必通过字符串执行此操作,则使用图像将解决您的解决方案。

标签: ios objective-c ios8 uibutton


【解决方案1】:

设置 UIButton contentEdgeInsets 将使您的按钮标题调整为上、左、下、右。

floatingButton.contentEdgeInsets = UIEdgeInsetsMake(top, left, bottom, right);

在你的情况下,它会使标题居中

floatingButton.contentEdgeInsets = UIEdgeInsetsMake(0, 2, 3, 0);

注意:根据您给定的代码,未提及 kFloatingButtonSize,我检查了 kFloatingButtonSize = 50

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    相关资源
    最近更新 更多