使用 CFStringGetHyphenationLocationBeforeIndex 添加连字符

2024-03-07

我正在制作一本带有核心文本的杂志,我试图自动在文本中添加连字符。我想我可以用这个功能来做到这一点

CFStringGetHyphenationLocationBeforeIndex

但它不起作用,我在网上找不到任何示例。

我想要做的是设置文本,如果我找到任何连字符位置,我会在那里放置一个“-”并通过访问器替换文本,以便它调用 setNeedsDisplay 并从头开始再次绘制。

- (void) setTexto:(NSAttributedString *)texto {

    _texto = texto;

    if (self.ctFrame != NULL) {
        CFRelease(self.ctFrame);
        self.ctFrame = NULL;
    }

    [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();   
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.bounds);
    CTFramesetterRef ctFrameSetterRef = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(_texto));
    self.ctFrame = CTFramesetterCreateFrame(ctFrameSetterRef, CFRangeMake(0, [_texto length]), path, NULL);

    NSArray *lines = (__bridge NSArray *)(CTFrameGetLines(self.ctFrame));

    CFIndex lineCount = [lines count];
    NSLog(@"lines: %d", lines.count);

    for(CFIndex idx = 0; idx < lineCount; idx++) {

        CTLineRef line = CFArrayGetValueAtIndex((CFArrayRef)lines, idx);

        CFRange lineStringRange = CTLineGetStringRange(line);
        NSRange lineRange = NSMakeRange(lineStringRange.location, lineStringRange.length);

        NSString* lineString = [self.texto.string substringWithRange:lineRange];

        CFStringRef localeIdent = CFSTR("es_ES");
        CFLocaleRef localeRef = CFLocaleCreate(kCFAllocatorDefault, localeIdent);

        NSUInteger breakAt = CFStringGetHyphenationLocationBeforeIndex((__bridge CFStringRef)lineString, lineRange.length, CFRangeMake(0, lineRange.length), 0, localeRef, NULL);

        if(breakAt!=-1) {
            NSRange replaceRange = NSMakeRange(lineRange.location+breakAt, 0);
            NSMutableAttributedString* attributedString = self.texto.mutableCopy;
            [attributedString replaceCharactersInRange:replaceRange withAttributedString:[[NSAttributedString alloc] initWithString:@"-"]];
            self.texto = attributedString.copy;
            break;
        } else {
            CGFloat ascent;
            CGFloat descent;
            CTLineGetTypographicBounds(line, &ascent, &descent, nil);
            CGContextSetTextPosition(context, 0.0, idx*-(ascent - 1 + descent)-ascent);
            CTLineDraw(line, context);
        }
    }
}

问题是它第二次进入drawRect(带有新文本)lines.count log 为0。而且我也不确定这是正确的方法。

也许还有另一种方法来修改 CTLines(在上一行的“-”后面添加剩余的字符)。


在创建属性字符串之前,您可以添加软连字符。然后就可以画图了。

我编写了一个类别,用于向任何字符串添加“软连字符”。这些是“-”,在渲染时不可见,而只是为 CoreText 或 UITextKit 排队以了解如何分解单词。

NSString *string = @"accessibility tests and frameworks checking";
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
NSString *hyphenatedString = [string softHyphenatedStringWithLocale:locale error:nil];
NSLog(@"%@", hyphenatedString);

Outputs ac-ces-si-bil-i-ty tests and frame-works check-ing


NSString+SoftHyphenation.h

typedef enum {
    NSStringSoftHyphenationErrorNotAvailableForLocale
} NSStringSoftHyphenationError;

extern NSString * const NSStringSoftHyphenationErrorDomain;
extern NSString * const NSStringSoftHyphenationToken;

@interface NSString (SoftHyphenation)

- (BOOL)canSoftHyphenateStringWithLocale:(NSLocale *)locale;
- (NSString *)softHyphenatedStringWithLocale:(NSLocale *)locale error:(out NSError **)error;

@end

NSString+SoftHyphenation.m

#import "NSString+SoftHyphenation.h"

NSString * const NSStringSoftHyphenationErrorDomain = @"NSStringSoftHyphenationErrorDomain";
NSString * const NSStringSoftHyphenationToken = @"­"; // NOTE: UTF-8 soft hyphen!

@implementation NSString (SoftHyphenation)

- (BOOL)canSoftHyphenateStringWithLocale:(NSLocale *)locale
{
    CFLocaleRef localeRef = (__bridge CFLocaleRef)(locale);
    return CFStringIsHyphenationAvailableForLocale(localeRef);
}

- (NSString *)softHyphenatedStringWithLocale:(NSLocale *)locale error:(out NSError **)error
{
    if(![self canSoftHyphenateStringWithLocale:locale])
    {
        if(error != NULL)
        {
            *error = [self hyphen_createOnlyError];
        }
        return [self copy];
    }
    else
    {
        NSMutableString *string = [self mutableCopy];
        unsigned char hyphenationLocations[string.length];
        memset(hyphenationLocations, 0, string.length);
        CFRange range = CFRangeMake(0, string.length);
        CFLocaleRef localeRef = (__bridge CFLocaleRef)(locale);

        for(int i = 0; i < string.length; i++)
        {
            CFIndex location = CFStringGetHyphenationLocationBeforeIndex((CFStringRef)string, i, range, 0, localeRef, NULL);

            if(location >= 0 && location < string.length)
            {
                hyphenationLocations[location] = 1;
            }
        }

        for(int i = string.length - 1; i > 0; i--)
        {
            if(hyphenationLocations[i])
            {

                [string insertString:NSStringSoftHyphenationToken atIndex:i];
            }
        }

        if(error != NULL) { *error = nil; }

        // Left here in case you want to test with visible results
        // return [string stringByReplacingOccurrencesOfString:NSStringSoftHyphenationToken withString:@"-"];
        return string;
    }
}

- (NSError *)hyphen_createOnlyError
{
    NSDictionary *userInfo = @{
                               NSLocalizedDescriptionKey: @"Hyphenation is not available for given locale",
                               NSLocalizedFailureReasonErrorKey: @"Hyphenation is not available for given locale",
                               NSLocalizedRecoverySuggestionErrorKey: @"You could try using a different locale even though it might not be 100% correct"
                               };
    return [NSError errorWithDomain:NSStringSoftHyphenationErrorDomain code:NSStringSoftHyphenationErrorNotAvailableForLocale userInfo:userInfo];
}

@end

希望这可以帮助 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 CFStringGetHyphenationLocationBeforeIndex 添加连字符 的相关文章

  • 企业发行版在 Swift 应用程序中与 iOS8 配合不佳

    我在使用 swift 应用程序在 iOS 8 设备上运行 Enterprise 版本时遇到问题 如果我使用非企业帐户进行代码签名 它似乎工作正常 有人遇到这个问题吗 以下是我在尝试使用企业帐户运行构建以进行协同设计时在 iOS 设备上收到的
  • 如何将相机中的图像保存到 iPhone 图库中的特定文件夹?

    嘿 我是 iPhone 新手 最近我一直在尝试制作一个应用程序 基本上 我想要做的是 如果用户将从相机捕获任何图像 那么它应该保存在设备库中 我知道如何将照片保存在图库中 它对我有用 但我无法将所有捕获的图像保存到设备图库中的特定文件夹 例
  • Swift Codable 将空 json 解码为 nil 或空对象

    这是我的代码 class LoginUserResponse Codable var result String var data LoginUserResponseData var mess String public class Log
  • 从命令行调试 iOS 应用程序构建

    我正在通过命令行构建 iOS 应用程序 但在调试它时遇到问题 如果我使用 XCode 进行构建 它会让我在设备上 构建和调试 而不会出现任何问题 但现在 我不知道如何使用 gdb 在设备上启动它并逐步执行它 如果我尝试 添加自定义目标 可执
  • Objective-c 中的块递归

    当执行涉及 Objective C 块的递归时 我在 iOS 应用程序中收到 EXC BAD ACCESS 信号 这是简化的代码 void problematicMethod FriendInfo friendInfo onComplete
  • 推入 UINavigationController 时隐藏 FBFriendPickerViewController 导航栏

    介绍一个实例FBFriendPickerViewController using presentViewController animated completion 非常简单 该类似乎是针对该用例的 但是 我想推送一个实例FBFriendP
  • 使用 Interface Builder 创建 UIScrollView 的步骤

    我正在尝试使用 UIScrollView 但似乎有一些基本的事情我不理解 假设我想在我的 iPhone 应用程序中使用 UIScrollView 我有一个充满按钮的视图 尺寸为 320x700 显然 这对于 320x480 的 iPhone
  • iOS 中的构建对象文件扩展名是什么?

    当我在项目中构建java对象类时 将创建带有 class扩展名的构建文件 并且人类不可读 快速构建文件怎么样 example car java gt build gt car class 构建后会是什么 car swift gt build
  • 如何恢复消耗品应用内购买?

    我正在开发一款 iOS 游戏 用户可以通过应用内消耗品购买一定数量的内部货币 比如 1000 金币 如果用户想将余额从一台设备转移到另一台设备 如何恢复消耗品购买 在苹果的文档中 它说我们必须使用我们自己的服务器 但是如何获取用户的Appl
  • 以编程方式触发iOS摇动事件

    如何以编程方式触发 iOS 中的摇动事件 我尝试过以下方法 但它总是崩溃 void shake NSLog TEST UIMotionEventProxy m NSClassFromString UIMotionEvent alloc in
  • iOS:提高图像绘制速度

    我有一系列想要制作动画的图像 UIImageView支持一些基本的动画 但不足以满足我的需求 我的第一个方法是使用UIImageView并设置image当图像属性 这太慢了 速度慢的原因是图像的绘制 这让我感到惊讶 我以为瓶颈会加载图像 我
  • 关于窗口层次结构的警告

    我的调试器中出现这样的警告 这是什么意思 Warning Attempt to present
  • 我的游戏中应该有多少个视图控制器?

    我开始使用 spritekit 构建我的第一个游戏 现在我只有一个视图控制器来呈现开始屏幕场景 override func viewDidLoad super viewDidLoad let scene StartScreenScene C
  • 频繁绘制 CGPath 时的性能

    我正在开发一个将数据可视化为折线图的 iOS 应用程序 该图被绘制为CGPath在全屏自定义中UIView最多包含 320 个数据点 数据经常更新 图表需要相应地重新绘制 刷新率为 10 秒就很好了 到目前为止很容易 然而 我的方法似乎需要
  • 来自 iPhone/iPad 的 json Web 服务

    有人可以帮助我解决如何从 iphone 或 ipad 使用 json Web 服务的问题吗 这里我的要求是使用 API 密钥实现 json webservice 如果可能的话发布一些教程或示例链接 谢谢 规范的 JSON 处理库是here
  • NVActivityIndi​​catorView 仅适用于特定视图

    我正在使用这个库https github com ninjaprox NVActivityIndi catorView https github com ninjaprox NVActivityIndicatorView用于显示加载指示器
  • 指定访问组时出现 KeychainItemWrapper 错误

    相当长一段时间以来 我一直在使用 KeychainItemWrapper 的 ARC 版本成功读取和写入私有钥匙串项目 我现在正在努力将我的 iOS 应用程序转换为使用共享访问组 以便我的 2 个共享相同应用程序前缀的应用程序可以访问钥匙串
  • git 提交错误:检测到大文件

    您好 我正在为 ios 8 1 开发一个应用程序 xcode 我已经使用 googleMaps 框架来实现自动完成功能 当我尝试在 Git 中推送我的项目时 我收到大文件检测错误 后来尝试使用 git lfs 并跟踪 git 检测到的文件
  • 避免 UIImage 的 imageNamed - 内存管理

    我正在经历这个链接 http akosma com 2009 01 28 10 iphone memory management tips 我遇到了一个点避免 UIImage 的 imageNamed 出于什么原因我们应该避免这种情况 它会
  • UIWebView Bug:-[UIWebView cut:]:无法识别的选择器发送到实例

    In the UIWebView 如果包含文本的输入元素具有焦点 并且按下按钮导致输入失去焦点 则随后双击输入以重新获得焦点并从出现的弹出栏中选择 剪切 或 复制 或 粘贴 会导致这UIWebView因错误而崩溃 UIWebView cut

随机推荐