【发布时间】:2015-06-17 13:40:20
【问题描述】:
我有一个 UILabel,如果可能的话,我想先缩小文本以适合单行。如果这不起作用,我希望它最多使用两行。这可能吗?
目前我的设置是这样的:
这是我的布局
如果我将行设置更改为 1 行,文本会缩小。
【问题讨论】:
标签: ios objective-c xcode autolayout
我有一个 UILabel,如果可能的话,我想先缩小文本以适合单行。如果这不起作用,我希望它最多使用两行。这可能吗?
目前我的设置是这样的:
这是我的布局
如果我将行设置更改为 1 行,文本会缩小。
【问题讨论】:
标签: ios objective-c xcode autolayout
我想出了一个解决方案。
下一部分是代码。我继承了 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) 的回答中获得了大部分代码
【讨论】: