UILabel textRectForBounds 在尝试创建边距时没有效果
我试图缩进 UILabel 中的文本,以便在显示背景颜色的文本周围留出一些边距。按照此处的建议,我已经重写了textRectForBounds:limitedToNumberOfLines:
,如下所示:
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect intermediate = CGRectMake(bounds.origin.x+MARGIN,bounds.origin.y+MARGIN,bounds.size.width-2*MARGIN,bounds.size.height-2*MARGIN);
return [super textRectForBounds:intermediate limitedToNumberOfLines:numberOfLines];
}
但无论我做什么,文本最终都会紧贴矩形的左边框。似乎绘图忽略了返回的 CGRect 的原始部分(尽管它似乎尊重宽度部分,就好像我将中间的宽度减小到例如 bounds.size.width-200
textRectForBounds 返回的矩形适当狭窄,并且文本绘制在一个细长的列中)。
那么:我还需要对 UILabel
做什么,以使绘图尊重 textForRectBounds
-returned-rect 的 origin.x 和 origin.y?如果可以的话,我宁愿不覆盖 UILabel
的 drawTextInRect
。
更新:这是很久以前的事了,我不记得为什么另一个问题对我不起作用。我相信这是因为我试图拥有一个包含多行的 UILabel
,并且解决方案 在这种情况下,here 不起作用。
I'm trying to indent the text in a UILabel to leave some margin around the text showing the background colour. Following the suggestion here I've overriden textRectForBounds:limitedToNumberOfLines:
like so:
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect intermediate = CGRectMake(bounds.origin.x+MARGIN,bounds.origin.y+MARGIN,bounds.size.width-2*MARGIN,bounds.size.height-2*MARGIN);
return [super textRectForBounds:intermediate limitedToNumberOfLines:numberOfLines];
}
But no matter what I do, the text ends up tight against the left border of the rectangle. It seems as though the drawing is ignoring the origin part of the returned CGRect (although it seems to be respecting the width part, as if I reduce to width of intermediate to eg bounds.size.width-200
the rect that textRectForBounds returns is suitably narrow and the text is drawn in a long skinny column).
So: what else I need to do to the UILabel
to make the drawing respect the textForRectBounds
-returned-rect's origin.x and origin.y? I'd rather not override UILabel
's drawTextInRect
if I can help it.
Update: This was a long time ago and I can't remember exactly why the other question didn't work for me. I believe it was because I was trying to have a UILabel
with multiple lines, and the solution here didn't work in that case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你应该像这样重写
textRectForBounds:limitedToNumberOfLines:
和drawTextInRect:
:I think you should override both
textRectForBounds:limitedToNumberOfLines:
anddrawTextInRect:
like this:查看文档,可能会有所帮助。对 super 的调用可能不会返回您假设的值。
祝你好运!
Check the documentation, it might be of some help. calls to super might not be returning the values you assume.
Good luck!