简体   繁体   中英

Rotate UIButton titleLabel without clipping

I'm trying to rotate the titleLabel of a UIButton by 45 degrees. The character in the text is '+'.

I can get the title to rotate with

button.titleLabel?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))

But then one end of the '+' symbol is clipped, as in the following screenshots.

在此处输入图片说明在此处输入图片说明

I found this , but I couldn't quite follow how the problem was fixed. It's strange that the clipped section still exists within the bounds of the other ends—it doesn't protrude outside the 'square' of the symbol.

I also tried to use Facebook's Pop library, which kind of worked, except I couldn't work out how to do a normal anti-clockwise or clockwise rotation. I used kPOPLayerRotation with M_PI_4 and it did something unexpected. I'm happy to use Pop if someone can provide sample code for basic clockwise/anticlockwise rotation.

A possibly related issue: the centre of the titleLabel moves as well. Is there an easy way to prevent this?

Thanks very much for your help.

You are rotating the button's titleLabel, which is inside of the button. Button wasn't rotated. but label was rotated. So You are getting the clip or center misalignment of label. I suggest you to rotate the button itself. So it will rotate its subviews as well.

// Check already it was rotated,transformed...?
if (CGAffineTransformIsIdentity(button.transform)) {

    //Yes, Reset to the original position and size.
    button.transform = CGAffineTransformIdentity;

}

//Apply rotation now
button.transform=CGAffineTransformMakeRotation(M_PI_4);

For anyone coming to this in the future, I ended up creating a new UIView (the blue rectangle) which contained the UIButton (the white '+'). I then disabled used interaction on the UIButton, and added a gesture recogniser to the UIView. When I wanted to rotate the '+', I rotated the whole UIButton (but not the containing UIView).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM