UIButton does not resize height correctly with custom font when sizeToFit is called

自作多情 提交于 2019-12-13 02:59:00

问题


I'm attempting to create a UIButton using a custom font. I set the titleLabel's font and then set my text, then call sizeToFit. Unfortunately, it resizes the height to a couple of pixels too small and shaves off part of each capital letter. The button's titleLabel has a smaller height than the size of the button itself, but setting its frame manually after calling sizeToFit isn't doing anything for me. I noticed the same behavior from a plain UILabel, except when I manually set the frame to the size of my UIButton, the text displayed perfectly. When I called sizeToFit, the UILabel became the same size as the UIButton's titleLabel, and it also cut off the top of my capital letters. Additionally, since this was a SpriteKit SKView I was adding these buttons to, I also created an SKLabelNode to see how it dealt with automatically sizing the font, and it did a perfect job, with its height being several pixels taller than both my UILabel and my UIButton's titleLabel height. Here's an imgur album to show it visually, where it's noticeable on the S and the dotting of the lowercase i:

http://imgur.com/a/fy5st

Does anyone have any ideas what is causing this to happen?


回答1:


In case anyone has the same problem and comes across this, I figured out a solution simply by subclassing UIButton. Then, I just modified layoutSubviews so that the titleLabel bounds equaled the button's subviews, and it no longer cut off the top part of the font. Not sure if it's the best way, but it works.

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.titleLabel.bounds = self.bounds;
}


来源:https://stackoverflow.com/questions/20978640/uibutton-does-not-resize-height-correctly-with-custom-font-when-sizetofit-is-cal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!