我可以绘制我的NSStrings,但是在绘制它时我无法调整大小。我的drawRect:方法是:
- (void)drawRect:(CGRect)rect
{
NSArray *objectArray = [NSArray arrayWithObjects:[UIFont systemFontOfSize:80.0f], nil];
NSArray *keyArray = [NSArray arrayWithObjects:@"NSFontAttributeName", nil];
NSMutableDictionary *textAttributes = [NSMutableDictionary dictionaryWithObjects:objectArray forKeys:keyArray];
NSString *myTestString = @"Test String";
[textAttributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
[myTestString drawAtPoint:CGPointMake(20, 30) withAttributes:textAttributes];
[myTestString drawInRect:CGRectMake(50, 50, 500, 500) withAttributes:textAttributes];
NSLog(@"wrote %@ with %@", myTestString, textAttributes);
}
textAttributes看起来很好,字体信息返回为:
NSFontAttributeName = "<UICTFont: 0x14eeff40> font-family: \".HelveticaNeueInterface-M3\"; font-weight: normal; font-style: normal; font-size: 80.00pt"
我可以使用attributes数组正确更改颜色,为什么这会导致文本默认为10pt大小?
答案 0 :(得分:1)
NSAttributedString是你想要的。 UICatalog示例代码有一个NSAttributedString用法示例:
#pragma mark - UIPickerViewDataSource
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSMutableAttributedString *attrTitle = nil;
// note: for the custom picker we use custom views instead of titles
if (pickerView == self.myPickerView)
{
if (row == 0)
{
NSString *title;
if (component == 0)
title = [self.pickerViewArray objectAtIndex:row];
else
title = [[NSNumber numberWithInt:row] stringValue];
// apply red text for normal state
attrTitle = [[NSMutableAttributedString alloc] initWithString:title];
[attrTitle addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(0, [attrTitle length])];
}
}
return attrTitle;
}
关于iOS的Stanford U MOOC课程(由Paul Hegarty和available on iTunes运行)概述了演讲4中NSAttributedString的使用。第5讲还介绍了您可以遵循的NSAttributedString代码演示。最后,github用户m2mtech发布了repositories of all code exercises and assignments for the course,您可以下载相关的项目文件here。