更改 NSString 的字体大小并加载到文本视图中

Change the font size of NSString and loading into text view

我有一个文本视图,它以 html 格式从服务器加载一些文本。 但是即使我在文本视图中设置文本的字体大小也没有改变,这可能是因为我目前正在根据服务器的文本内容计算文本视图的高度。

这是代码

    itemDescribtionView = [[[UIView alloc]init] autorelease];
    [itemDescribtionView setBackgroundColor:[UIColor whiteColor]];
    [mainPageScrollView addSubview:itemDescribtionView];

    NSString * itemDescribtionStr = [NSString stringWithFormat:@"%@",[[delegate.detailPageArray objectAtIndex:delegate.detailArraySelectedIndex]objectForKey:@"item_description"]];


    NSAttributedString *attributedString = [[NSAttributedString alloc]
                                            initWithData: [itemDescribtionStr dataUsingEncoding:NSUnicodeStringEncoding]
                                            options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                            documentAttributes: nil
                                            error: nil];

    UITextView * itemDescriptionTextView = [[[UITextView alloc]init]autorelease];
    [itemDescriptionTextView setDataDetectorTypes:UIDataDetectorTypeLink];
    [itemDescriptionTextView setDelegate:self];
    [itemDescriptionTextView setFont:[UIFont fontWithName:appFontRegular size:18]];
    [itemDescriptionTextView setUserInteractionEnabled:YES];
    [itemDescriptionTextView setScrollEnabled:NO];
    [itemDescriptionTextView setEditable:NO];
    [itemDescriptionTextView setAttributedText:attributedString];
    [itemDescriptionTextView setFrame:CGRectMake(10,0,delegate.windowWidth-20,[self heightForAttributedString:attributedString maxWidth:delegate.windowWidth-20])];
    itemDescriptionTextView.contentInset = UIEdgeInsetsMake(-7.0,0.0,0,0.0);
    [itemDescribtionView addSubview:itemDescriptionTextView];

- (CGFloat)heightForAttributedString:(NSAttributedString *)text maxWidth:(CGFloat)maxWidth {

NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGSize size = [text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:options  context:nil].size;
NSLog(@"newtext %@",newtext);
NSLog(@"text %@",text);
CGFloat height = size.height + 1; // add 1 point as padding

NSLog(@"%f",height);
if(height<30)
{
    height = 30;
}
return height;
 }

我尝试在 itemDescriptionTextView 中的 setFrame 之后设置字体,它确实改变了字体大小,但是文本视图的高度不够大,无法显示所有文本。

所以我试图在计算文本视图的高度之前更改字体。但到目前为止我没有运气。并想看看是否有人可以指导我。谢谢。

在创建 itemDescriptionTextView 之前,请像这样在属性字符串上设置字体。

[attributedString addAttributes:@{NSFontAttributeName: [UIFont fontWithName:appFontRegular size:18]} range:NSMakeRange(0, attributedString.length)];