UILabel autoshrink并使用2行,如果有必要
我有一个UILabel,我想先缩小文本,如果可能的话适合单行。 如果这不起作用,我希望最多使用两行。 这可能吗?
目前与设置我有它这样做:
这是我的布局
如果我将行设置更改为1行,文本会缩小。
我想出了一个解决scheme。
- 将“线条”设置为2
- 将“换行”设置为“截尾”
- 将“自动缩放”设置为“最小字体缩放”,并将该值设置为0.1(或者您希望的最小值)
- (可选)选中“拧紧字母间距”
下一部分是在代码中。 我分类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,它的尺寸就会正确,并且只有在必要的时候才会有两行。
我从这个问题( https://stackoverflow.com/a/11788385/758083 )得到了john.k.doe的大部分代码,
- 排列三个UILabels彼此相邻,每个标签可以是多行
- '无法在descriptionForLayoutAttribute_layoutItem_coefficient中创build描述。 有些东西是零“
- 在容器视图中加载ViewController
- 如何自动布局iphone中的uiview控制器中的button?
- 如何定位相对于包含视图大小的子视图?
- 自动调整uitableviewcell – SWIFT
- UIView addSubview自动布局不工作
- UITableViewCell四舍五入错误与NSAutoresizingMaskLayoutConstraint,但大小正确设置在故事板和heightForRowAtIndexPath:
- 如何根据XIB中子视图的大小调整超级视图的高度?