if ([cell.waveTextLabel respondsToSelector:@selector(setAttributedText:)])
{
const CGFloat fontSize = 16.0f;
//define attributes
UIFont *boldFont = [UIFont fontWithName:@"HelveticaNeue-Medium" size:fontSize];
// Create the attributes
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:boldFont, NSFontAttributeName, nil];
NSRange rangeOfIs = [cell.cellWaveObject.waveString rangeOfString:@" is"];
NSLog(@"The range of is: {%lu, %lu}", (unsigned long)rangeOfIs.location, (unsigned long)rangeOfIs.length);
NSRange nameRange = NSMakeRange(0, rangeOfIs.location);
NSLog(@"The range of the name: {%lu, %lu}", (unsigned long)nameRange.location, (unsigned long)nameRange.length);
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:cell.cellWaveObject.waveString];
[attributedString setAttributes:attrs range:nameRange];
//set the label text
[cell.waveTextLabel setAttributedText:attributedString];
}
我设置了一个异常断点,它在线上崩溃了
[attributedString setAttributes:attrs range:nameRange];
有人知道我该如何解决这个问题吗?
在您的代码中,问题可能与设置属性的范围的计算有关。具体来说,当您计算 nameRange 时,您使用 rangeOfIs 的 location 属性作为范围的长度。如果 rangeOfIs 不包含子字符串“is”,这可能会导致越界错误,非常明显。
要解决此问题,
在尝试设置范围之前,您应该检查cell.cellWaveObject.waveString
中是否存在子字符串“is”。此外,您还应该确保rangeOfIs.location不等于NSNotFound,表明已找到子字符串。以下是您可以修改代码来处理此问题的方法:
if ([cell.waveTextLabel respondsToSelector:@selector(setAttributedText:)]) {
const CGFloat fontSize = 16.0f;
UIFont *boldFont = [UIFont fontWithName:@"HelveticaNeue-Medium" size:fontSize];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:boldFont, NSFontAttributeName, nil];
NSRange rangeOfIs = [cell.cellWaveObject.waveString rangeOfString:@" is"];
// Check if " is" substring exists and its location is not NSNotFound
if (rangeOfIs.location != NSNotFound) {
NSRange nameRange = NSMakeRange(0, rangeOfIs.location);
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:cell.cellWaveObject.waveString];
[attributedString setAttributes:attrs range:nameRange];
[cell.waveTextLabel setAttributedText:attributedString];
} else {
// Handle case when " is" substring is not found
NSLog(@"Substring ' is' not found in wave string");
// You may want to set a default attributed text or handle it differently
}
}
此修改可确保您为属性设置的范围在字符串的范围内,并处理在 cell.cellWaveObject.waveString
中找不到子字符串“is”的情况。