我有一个UILabel我希望首先缩小文本以适应单行,如果可能的话。如果这不起作用,我希望它最多使用两行。这可能吗?
目前我使用的设置是:
这是我的布局
如果我将线条设置更改为1行,则文本会缩小。
答案 0 :(得分:3)
我想出了一个解决方案。
下一部分是代码。我将UILabel分类并提出了这个问题。
#import <UIKit/UIKit.h>
@interface HMFMultiLineAutoShrinkLabel : UILabel
- (void)autoShrink;
@end
#import "HMFMultiLineAutoShrinkLabel.h"
@interface HMFMultiLineAutoShrinkLabel ()
@property (readonly, nonatomic) UIFont* originalFont;
@end
@implementation HMFMultiLineAutoShrinkLabel
@synthesize originalFont = _originalFont;
- (UIFont*)originalFont { return _originalFont ? _originalFont : (_originalFont = self.font); }
- (void)autoShrink {
UIFont* font = self.originalFont;
CGSize frameSize = self.frame.size;
CGFloat testFontSize = _originalFont.pointSize;
for (; testFontSize >= self.minimumScaleFactor * self.font.pointSize; testFontSize -= 0.5)
{
CGSize constraintSize = CGSizeMake(frameSize.width, MAXFLOAT);
CGRect testRect = [self.text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:nil];
CGSize testFrameSize = testRect.size;
// the ratio of testFontSize to original font-size sort of accounts for number of lines
if (testFrameSize.height <= frameSize.height * (testFontSize/_originalFont.pointSize))
break;
}
self.font = font;
[self setNeedsLayout];
}
@end
然后,当您更改标签文本时,只需调用autoShrink,它的大小将正确,并且只在必要时才会显示两行。
我从john.k.doe得到了大部分代码来自这个问题的回答(https://stackoverflow.com/a/11788385/758083)