我在使用UILabel attributedText
时遇到了麻烦,我现在正在考虑创建一个UIView子类,它在drawRect
中手动渲染其属性字符串。
我遇到的问题的要点是故事板文件中定义的UILabels似乎总是在运行时呈现大小为17.0的字体。我已经尝试了很多黑客来解决这个问题,但没有任何效果。无论我做什么,标签的字体大小都保持在17.0。
size
,但显然NSFontAttributeName
下的所有内容都是不可变的。我对可能导致这个问题的原因有很多怀疑。我很好奇它是否与标签视图在UITableViewCell子类中的事实有关,但我没有时间运行大量实验。我通常没有充分利用带有属性文本的UILabel,但我没有在这里或其他地方找到有关已知问题的证据。
我已经仔细查看了所有API,尝试禁用某些自动换行设置,并尝试将Plain标签的字体大小设置为14.0,然后将其标记为属性,因为我认为可能更高级别的属性可以覆盖较低级别的归属文本设置。再一次,这种方法并不成功。
还有其他人经历过这样的事吗?
在此期间,我将继续实现我自己的属性标签作为UIView子类。如果这最终成为目前唯一可行的解决方案,我将发布代码。
我不知道你是如何设置标签中的文字的,但是如果你用一个字体属性设置为你想要的属性字符串来设置它,它就会起作用。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSString *plain = self.theData[indexPath.row];
cell.label.attributedText = [[NSAttributedString alloc] initWithString:plain attributes:@{NSFontAttributeName:[UIFont fontWithName:@"Snell Roundhand" size:24]}];
return cell;
}
当我尝试在故事板中设置标签以使用属性文本时,我看到了同样的问题。
如上所述,这是我最终使用的解决方案。它在各个方面都不像UILabel那样多功能(不支持缩小字体等),但结果证明它适合我的需要。
@interface DHAttributedLabel : UIView
@property (nonatomic, strong) NSAttributedString * attributedText;
@end
@implementation DHAttributedLabel
-(id) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setBackgroundColor:[UIColor clearColor]];
}
return self;
}
-(void) drawRect:(CGRect)rect {
CGRect boundingRect = [_attributedText
boundingRectWithSize : CGSizeMake(rect.size.width, CGFLOAT_MAX)
options : NSStringDrawingUsesLineFragmentOrigin
context : nil
];
CGRect drawInRect = rect;
CGFloat dy = .5 * (rect.size.height - boundingRect.size.height);
if (dy > 0) { // center vertically if appropriate
drawInRect.origin.y += dy; // (truncate bottom if the text is too big)
}
[_attributedText drawInRect:drawInRect];
}
@end
我通过在UITableViewDataSource attributedText
方法中设置cellForRowAtIndexPath:
解决了同样的问题。似乎如果在委托返回单元格之前通过IBOutlet设置attributedText
属性,则某些referencedText属性将丢失(如属性substring的字体大小),而其他属性则被保留(如属性substring的文本颜色)。
在我看来是某种UIKit问题。
在我的情况下,它在attributedText
中设置tableView(_:willDisplay:forRowAt:)
时起作用。
具有HTML内容的归属文本,意味着他们在其内容中指定了自己的字体。
要增加Label属性Text的大小,您需要通过CSS覆盖html字体。
以下是您获得的内容,即HTMl内容。
<html><body><font face='Helvetica' size='3'>There is no description.</html></body>
正如您所看到的,他们已经在HTML内容中给出了大小您需要添加额外的属性来覆盖这样的字体。
<style>
html * {font-size: 25.0pt !important;}
</style>
<html><body><font face='Helvetica' size='13'>There is no description.</html></body>
通过添加此CSS,尝试在Label中获取属性String,Set。
希望这会将字体大小增加到25.0。