文本不是中心在圆形UI按钮 - ObjectiveC中对齐

时间:2016-10-26 07:22:33

标签: ios objective-c ios8 uibutton

我使用以下代码创建了一个浮动图标。

- (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];
}

我的输出是这样的:

enter image description here

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

1 个答案:

答案 0 :(得分:2)

设置UIButton contentEdgeInsets将使您的按钮标题调整为顶部,左侧,底部,右侧。

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

在您的情况下,它将成为中心的标题

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

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

enter image description here