gpt4 book ai didi

iphone - CoreText 映射字符

转载 作者:行者123 更新时间:2023-12-03 18:32:54 24 4
gpt4 key购买 nike

我在触摸处理程序中有一些,它响应我在其中绘制了一些属性文本的 View 上的点击。通过这个,我已经有了一个 CTRunRef (以及相关的行)以及该运行中的字形数量。

我无法轻松弄清楚的是,如何获取该运行的字形,并根据我的属性字符串,将其映射到字符串中的字符。

具体来说,问题是我想知道用户在 View 中点击了哪个单词,这样我就可以处理该单词是否是 URL 并触发自定义委托(delegate)方法,以便我可以用它打开 Web View 。我有所有可能的子字符串,我只是不知道如何将用户点击的位置映射到特定的子字符串。

任何帮助将不胜感激。

更新:实际上,根据 stackoverflow 上另一个人的建议,我采用了不同的方式。基本上,我所做的就是设置一个自定义属性 @"MyAppLinkAddress" 以及我在将字符串转换为属性字符串时找到的 URL 的值。这发生在我绘制字符串之前。因此,当发生点击事件时,我只是检查该属性是否存在,如果存在,则调用我的委托(delegate)方法,如果不存在,则忽略它。它现在正在按照我想要的方式工作,但我将把这个问题再留几天,如果有人能想出答案,如果它是一个可行的解决方案,我会很乐意接受它,以便其他人也许在将来的某个时候会发现这些信息很有用。

最佳答案

正如我在更新中提到的,我选择走不同的路线。相反,我想到在属性字符串中使用自定义属性来指定我的链接,因为无论如何我在创建时就有了它。所以我就这么做了。然后在我的触摸处理程序中,当点击运行时,我检查该运行是否具有该属性,如果是,则使用它调用我的委托(delegate)。从那里我很高兴地使用该 URL 加载 Web View 。

编辑:下面是解释我在这个答案中所做的事情的代码片段。享受吧。

// When creating the attribute on your text store. Assumes you have the URL already. 
// Filled in for convenience
NSRange urlRange = [tmpString rangeOfString:@"http://www.foo.com/"];
[self.textStore addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[UIColor blueColor].CGColor range:urlRange];
[self.textStore addAttribute:@"CustomLinkAddress" value:urlString range:urlRange];

然后...

// Touch handling code — Uses gesture recognizers, not old school touch handling.
// This is just a dump of code actually in use, read through it, ask questions if you
// don't understand it. I'll do my best to put it in context.
- (void)receivedTap:(UITapGestureRecognizer*)tapRecognizer
{
CGPoint point = [tapRecognizer locationInView:self];

if(CGRectContainsPoint(textRect, point))
{
CGContextRef context = UIGraphicsGetCurrentContext();

point.y = CGRectGetHeight(self.contentView.bounds) - kCellNameLabelHeight - point.y;

CFArrayRef lines = CTFrameGetLines(ctframe);
CFIndex lineCount = CFArrayGetCount(lines);
CGPoint origins[lineCount];
CTFrameGetLineOrigins(ctframe, CFRangeMake(0, 0), origins);
for(CFIndex idx = 0; idx < lineCount; idx++)
{
CTLineRef line = CFArrayGetValueAtIndex(lines, idx);
CGRect lineBounds = CTLineGetImageBounds(line, context);
lineBounds.origin.y += origins[idx].y;

if(CGRectContainsPoint(lineBounds, point))
{
CFArrayRef runs = CTLineGetGlyphRuns(line);
for(CFIndex j = 0; j < CFArrayGetCount(runs); j++)
{
CTRunRef run = CFArrayGetValueAtIndex(runs, j);
NSDictionary* attributes = (NSDictionary*)CTRunGetAttributes(run);
NSString* urlString = [attributes objectForKey:@"CustomLinkAddress"];
if(urlString && ![urlString isEqualToString:@""])
{
[self.delegate didReceiveURL:[NSURL URLWithString:urlString]];
UIGraphicsPopContext();
return;
}
}
}
}
UIGraphicsPopContext();
}
}

关于iphone - CoreText 映射字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3822572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com