使用 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 添加连字符 的相关文章

  • 最小的 iOS 蓝牙管理器示例

    我一直在构建一个最小的示例 用于使用 iOS 5 0 中的 BluetoothManager 私有框架来检测附近的蓝牙设备 使用此问题中找到的答案 寻找触手可及的通用蓝牙设备 https stackoverflow com question
  • 是否有针对不同屏幕尺寸的单独故事板?

    基本上我已经完成了一个应用程序 我唯一的问题是 ATM 机应用程序在设计时只考虑了 4 英寸显示屏 当在 3 5 英寸模拟器上运行时 应用程序会丢失 0 5 英寸 显然 那么我的问题是 如何在 Xcode 5 中为不同的屏幕尺寸设置不同的故
  • 如何在IOS中的UIStackView中设置权重

    UIStackView与安卓类似LinearLayout但我不知道如何设置子视图的权重 假设我有一个垂直的UIStackView and 3 UIImageView就在里面 我想连续设置权重3 6 1UIImageViews 我怎么做 UI
  • XMPPFramework - 如何创建多用户聊天室?

    我如何使用XMPPFramework在iPhone中实现GroupChat 我尝试了以下代码 但房间没有创建 我如何知道房间是否创建 XMPPRoomDelegate没有被调用 当Stream断开连接时 调用handleDidLeaveRo
  • 在 Objective-C 中比较 2 个字符串

    我写了以下代码 if depSelectedIndice gt 1 comSelectedIndice gt 1 NSLog depart elemet d depSelectedIndice NSLog depart elemet d c
  • 将永久字符添加到 UITextField

    有没有办法将字母永久添加到 UITextField 中 用户无法删除它 我想添加一个字符 用户无法删除它 但他们仍然可以在之后添加字母 Cheers 附注这是适用于 iOS 的 A UITextField有一个名为 应该更改范围内的字符 的
  • 如何打开定位服务

    当有人第一次拒绝时 如何从实际应用程序重新打开定位服务 我可以选择关闭或打开它 您只能提示他们在屏幕上打开定位服务 如下所示 UIApplication sharedApplication openURL NSURL URLWithStri
  • NSString – 静态还是内联?有性能提升吗?

    如果我写的话会有任何性能提升吗 NSString helloStringWithName NSString name static NSString formatString Hello return NSString stringWith
  • 打乱 NSMutableArray 而不重复并显示在 UIButton 中

    在我看来 我有 12 个按钮 一个数组包含 6 个名称 我想在其中打印数组名称UIButton标题 这是我的代码 texts NSMutableArray alloc initWithObjects 1 2 3 4 5 6 nil UIBu
  • 网站在 iPhone 屏幕右侧显示空白区域

    我遇到问题http eiglaw com http eiglaw com iPhone 屏幕右侧显示约 25 像素宽的空白 边框 我在 stackoverflow 上研究了这个问题 这些帖子是相关的 但是当我尝试提供的各种解决方案时 我无法
  • 如何在 Firebase 控制台中使用 Apple 新的 APN .p8 证书

    随着最近 Apple 开发者帐户的升级 我面临着一个困难 在尝试创建推送通知证书时 它为我提供了 p8 证书 而不是可以导出到 p12 的 APNs 证书 Firebase 控制台仅接受 p12 证书 那么我如何从这些新的 p8 证书中获取
  • 如何知道我的应用程序使用了多少 iCloud 空间?

    有没有办法查看我的应用程序正在备份到 iCloud 的内容以及它消耗了多少内存 Settings gt iCloud gt Storage Backup gt Manage Storage将显示正在备份的总计内容 iOS 会备份位于应用程序
  • 导入 RNCryptor 后架构 armv7 的未定义符号

    我导入了 RNCryptor 可以在这里找到 https github com rnapier RNCryptor https github com rnapier RNCryptor进入我的应用程序 但是 我在日志中收到了三个错误 Und
  • UIScrollView setZoomScale 将应用的旋转设置回零

    我已经从事地图替换工作很长一段时间了 整个事情的工作原理是UIScrollView由一个支持CATiledLayer 为了旋转我的地图 我旋转图层本身 使用CATransform3DMakeRotation 到目前为止效果很好 但如果我打电
  • 如何将 UILabel 的值绑定到实例变量?

    我是 mac objective c 的新手 我的问题是 我想知道是否可以将 UILabel 文本绑定到变量 而不必在值更改时手动设置文本 例如 在 Mac OS 上 当我打开新的 Finder 窗口并删除文件时 任务栏中的全局可用空间就会
  • 减少 CoreData 的调试输出?

    我正在开发一个使用 CoreData 的 iOS macOS 项目 它工作正常 但它会向控制台输出大量调试信息 这使得控制台无法使用 因为我的打印语句隐藏在所有与 CoreData 相关的内容中 我有一个非常简单的 CoreData 设置
  • 推送动画,没有阴影和停电

    我有一个简单的iOS NavigationController基于应用程序 二UICollectionViews 相继 如果元素打开 第一个合集 被点击时 第二集 将被打开 非常简单 重要的提示 Both UICollectionViews
  • 哪些 Flutter 插件或功能可以利用外部 iOS/Android 显示器来显示与主显示器不同的内容

    我正在构建一个跨平台应用程序 需要在外部显示器上显示不同的视图 通常通过连接到 LCD 投影仪的 HDMI 适配器电缆连接 Flutter 是否能够在内置的外部显示器上显示不同的屏幕 在现有的 Flutter 插件中还是使用现有的 Flut
  • 在 iOS 7 Safari 中,如何区分通过边缘滑动与后退/前进按钮的 popstate 事件?

    在 iOS 7 Safari 中 现在有两种后退 前进导航方式 使用底部的传统后退 前进按钮箭头或从屏幕边缘滑动 我正在使用动画在 ajax 应用程序中的页面之间进行转换 但如果用户通过边缘滑动进行导航 我不想触发该转换 因为这本身就是一个
  • iOS - UITableViewCell 使文本加粗

    我有一个字符串 NSString userInfo James Johnson james 我想做的就是大胆James Johnson并保留 james正常字体 所以我尝试过的是使用NSAttributedString但为了完成这个过程 我

随机推荐