RahulMishra RahulMishra - 1 year ago 80
Objective-C Question

Text is not center Aligned in Rounded UI Button - ObjectiveC

I have made a floating icon using following code.

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

My output is like that:

enter image description here

I am not able to bring the
in center.

Answer Source

Set UIButton contentEdgeInsets will make your button title adjustments to top, left, bottom, right.

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

In your case, it will make title to center

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

Note: as per your given code kFloatingButtonSize is not mentioned, i checked with kFloatingButtonSize = 50

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download