gpt4 book ai didi

ios - CATextLayer 中的 NSAttributedString 导致 EXC_BAD_ACCESS (ios 5.0)

转载 作者:行者123 更新时间:2023-12-01 18:23:16 25 4
gpt4 key购买 nike

我很难使用 CoreText。
不知道是我做错了什么还是iOS自己的错误,但这就是我所拥有的:
在 iOS 5.0 中,此代码使应用程序在显示 View 时崩溃

- (void)viewDidLoad
{
[super viewDidLoad];

UIFont * font = [UIFont systemFontOfSize:[UIFont systemFontSize]];

NSDictionary * attrs = @{(NSString *)kCTFontAttributeName:font};

NSAttributedString * attrStr = [[NSAttributedString alloc] initWithString:@"Test" attributes:attrs];

CATextLayer * textLayer = [[CATextLayer alloc] init];

textLayer.frame = self.view.frame;

textLayer.string = attrStr;

[self.view.layer addSublayer:textLayer];
}

它使 EXC_BAD_ACCESS 并打开 CoreText TAttributes::TAttributes(__CFDictionary const*):显示发生异常的汇编程序行。

难道我做错了什么?我挣扎了将近 8 个小时,但仍然不知道发生了什么。

更新

似乎问题是基于这条线
    NSDictionary * attrs = @{(NSString *)kCTFontAttributeName:font};

因为当我删除 Font 属性并添加 ForegroundColor 属性时,它突然开始工作。我会尝试深入挖掘,但仍然需要一些帮助。

最佳答案

如果你直接使用 Core Text,你必须使用 CTFont,而不是 UIFont。它们不是相互兼容的(即它们之间没有免费的桥梁)。

我花了一整天的时间才发现这一点。我的问题就像你现在遇到的一样!

不幸的是,美妙的 NSAttributedString 仅适用于 iOS 6。因此,如果您想制作一个多样式字符串并在 iOS 5 中显示它,那么您所做的是正确的。但您必须仅使用与 iOS 5 兼容的调用。

下面是一些用于制作与 CoreText 一起使用的 NSAttributedString 的典型代码,并且可以由 iOS 5 上的 CATextLayer 显示:

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/iOS5bookExamples/ch23p689styledText1/p579p593styleText1/RootViewController.m

关于ios - CATextLayer 中的 NSAttributedString 导致 EXC_BAD_ACCESS (ios 5.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15814622/

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