Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center UIButton text for floating action button like Inbox app

floatingButton = UIButton(x: blocx, y:blocy, width: imageSize, height: imageSize, target: self, action: "clickedFloatingButton")
floatingButton!.backgroundColor = CozyColors.StatCardSkip
floatingButton!.layer.cornerRadius = floatingButton!.frame.size.width / 2
floatingButton!.setTitle("+", forState: UIControlState.Normal)
floatingButton!.setTitleColor(CozyColors.ThemeWhite, forState: UIControlState.Normal)
floatingButton!.titleLabel?.font = UIFont(name: CozyStyles.ThemeFontName, size: imageSize*2/3)
view.addSubview(floatingButton!)

Here is the result:

inbox app floating button action

As you can see the plus button is not aligned properly to the center. How can I put it right in the middle without adding a UILabel as a subview?

like image 763
Esqarrouth Avatar asked Feb 10 '23 18:02

Esqarrouth


2 Answers

Try this code :

    var floatingButton = UIButton(frame: CGRectMake(10, 20, 50, 50))
    floatingButton.backgroundColor = UIColor.redColor()
    floatingButton.layer.cornerRadius = floatingButton.frame.size.width / 2
    floatingButton.setTitle("+", forState: UIControlState.Normal)
    floatingButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
    floatingButton.titleLabel?.font = UIFont(name: floatingButton.titleLabel!.font.familyName , size: 50)
    floatingButton.titleEdgeInsets = UIEdgeInsetsMake(-10, 0, 0, 0)
    view.addSubview(floatingButton)
like image 126
Ashish Kakkad Avatar answered Feb 12 '23 08:02

Ashish Kakkad


Well,I think a easier way is just set a background image for it

    floatingButton.setBackgroundImage(UIImage(named: "icon.png"), forState: UIControlState.Normal)

You can apply the transform or find a similar image from google

enter image description here

And the background image is here

enter image description here

like image 30
Leo Avatar answered Feb 12 '23 08:02

Leo