可能重复,但以下可接受的答案是一种简单的单功能解决方案。
我正在尝试制作新闻文章详细信息视图控制器,以在顶部显示文章的图像,然后显示日期,然后显示详细说明。
我了解到,我必须使用NSAttributedString
并且只有一个才能使用UITextView
。现在一切正常,但是我现在只有一个问题:图像宽度不适合屏幕宽度(或TextView宽度),请参见以下图像:
我尝试了一切,但没有任何效果。
如何使图像适合屏幕宽度?
提前致谢。
再次编辑这是涉及的代码:
#import "SingleNewsViewController.h"
@interface SingleNewsViewController ()
@end
@implementation SingleNewsViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSAttributedString *image = [self imageString];
NSAttributedString *date = [self dateString];
NSAttributedString *body = [self bodyString];
NSMutableAttributedString *wholeStory = [NSMutableAttributedString new];
// TODO: can you be sure image, date and body are all non-nil?
NSArray *allComponents = @[image, date, body];
for(NSAttributedString *component in allComponents)
{
[wholeStory appendAttributedString:component];
if(component != [allComponents lastObject])
[[wholeStory mutableString] appendString:@"\n\n"];
}
self.tv.attributedText = wholeStory;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UIImage *)image
{
return [UIImage imageNamed:@"latest_news_img.jpg"];
}
- (NSString *)dateText
{
return @"Hi There, this is date!";
}
- (NSString *)bodyText
{
return @"Hi There, this is body text!Hi There, .....";
}
- (NSAttributedString *)imageString
{
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [self image];
return [NSAttributedString attributedStringWithAttachment:textAttachment];
}
- (NSAttributedString *)dateString
{
return [[NSAttributedString alloc]
initWithString:[self dateText]
/*attributes:
@{
NSFontAttributeName: [UIFont preferredFontForTextStyle: UIFontTextStyleSubheadline],
... etc ...
}*/];
}
- (NSAttributedString *)bodyString
{
return [[NSAttributedString alloc]
initWithString:[self bodyText]
/*attributes:
@{
NSFontAttributeName: [UIFont preferredFontForTextStyle: UIFontTextStyleBody],
... etc ...
}*/];
}
@end
哦对了,所以NSTextAttachment
没有图像视图...啊...好吧,然后想到了另一个想法。如何重新整理UIImage
数据,然后将该图像传递到NSTextAttachment
,如本文所示:
使用此方法相应地调整图像大小:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句