顶部标签显示UILabel 在文本左对齐且标签保持其固有内容大小时的默认行为。底部标签是UILabel 的一个简单(几乎是微不足道的)子类。底部标签不夹“j”或“l”;相反,它为文本在左右边缘提供了一些喘息的空间,而无需居中对齐文本(糟糕)。
虽然标签本身在屏幕上没有显示对齐,但它们的文本显示是对齐的;更重要的是,在 IB 中,标签的左边缘实际上是对齐的,因为我在 UILabel 子类中覆盖了 alignmentRectInsets。
下面是配置这两个标签的代码:
#import "ViewController.h"
#import "NonClippingLabel.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *topLabel;
@property (weak, nonatomic) IBOutlet NonClippingLabel *bottomLabel;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *string = @"jupiter ariel";
UIFont *font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:28];
NSDictionary *attributes = @{NSFontAttributeName: font};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:string attributes:attributes];
self.topLabel.attributedText = attrString;
self.bottomLabel.attributedText = attrString;
}
这是NonClippingLabel子类的实现:
#import <UIKit/UIKit.h>
@interface NonClippingLabel : UILabel
@end
@implementation NonClippingLabel
#define GUTTER 4.0f // make this large enough to accommodate the largest font in your app
- (void)drawRect:(CGRect)rect
{
// fixes word wrapping issue
CGRect newRect = rect;
newRect.origin.x = rect.origin.x + GUTTER;
newRect.size.width = rect.size.width - 2 * GUTTER;
[self.attributedText drawInRect:newRect];
}
- (UIEdgeInsets)alignmentRectInsets
{
return UIEdgeInsetsMake(0, GUTTER, 0, GUTTER);
}
- (CGSize)intrinsicContentSize
{
CGSize size = [super intrinsicContentSize];
size.width += 2 * GUTTER;
return size;
}
@end
不编辑字体文件,不使用Core Text;对于那些使用 iOS 6+ 和 Auto Layout 的用户来说,这只是一个相对简单的 UILabel 子类。
更新:
Augie 发现我的原始解决方案阻止了多行文本的自动换行。我通过使用drawInRect: 而不是drawAtPoint: 在标签的drawRect: 方法中绘制文本来解决了这个问题。
截图如下:
顶部标签是普通的UILabel。底部标签是NonClippingLabel,具有极端的装订线设置,以适应尺寸为 22.0 的 Zapfino。两个标签都使用自动布局左右对齐。