UILabel 获取文本子字符串的 CGRect
我的目标很简单:从 UILabel 获取标签文本中子字符串的矩形。从广泛的搜索来看,似乎没有任何内置的东西可以处理这个问题。其他人也提出过类似的问题,但在 Stackoverflow 上都没有得到完整的回答。
// Something like this perhaps (added as a category)
CGRect rect = [myLabel rectForRange:NSMakeRange(3, 5)];
它的用途示例(只是为了澄清我正在搜索的内容):
My objective is simple: From a UILabel get the rect of a substring in the text of the label. From extensive searching there doesn't appear to be anything built in to handle this. Other people have asked similar questions, but none have been answered fully here on Stackoverflow.
// Something like this perhaps (added as a category)
CGRect rect = [myLabel rectForRange:NSMakeRange(3, 5)];
An example of what it could be used for (just to clarify what I'm searching for):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
雨的味道风的声音2024-12-03 04:27:47
你是对的:这不是 UILabel
的内置部分。
如果你确实需要这个,子类 UILabel
,使用 CoreText
实现 -drawRect:
,你将能够 通过CTLineGetOffsetForStringIndex()计算范围的矩形
, CTFrameGetLineOrigins()
和 CTLineGetTypgraphicBounds()
。如果范围内的文本被布置为跨越换行符,这将变得复杂;你可能需要多个矩形。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这主要是一个字符矩形所需要的,所以我疯狂地编写了一些代码,可以准确计算最基本的 UILabel 的矩形。标准 UILineBreakMode 和文本对齐方式。
我希望如果我将它发布给公众,人们的代码会对其做出贡献并改进它,特别是因为我对文本渲染不太了解!
代码:
https://gist.github.com/1278483
This was mostly needed for one character rects, so I went crazy and wrote some code that could accurately calculate the rect for the most basic UILabel. Standard UILineBreakMode and text alignment.
I was hoping that if I release it to the public people code contribute to it and improve it, especially since I don't know so much about text rendering!
The code:
https://gist.github.com/1278483