我有一个UILabel,我想在顶部和底部添加空格。在限制最小高度的情况下,我将其修改为:
为了做到这一点,我使用了:
override func drawTextInRect(rect: CGRect) {
var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
但我必须找到不同的方法,因为如果我写了超过两行,问题是一样的:
objective - c
基于Tai Le的回答,它在一个Interface Builder Designable中实现了这个特性,下面是Objective-C版本。
把这个放在YourLabel.h文件中:
@interface YourLabel : UILabel
@property IBInspectable CGFloat topInset;
@property IBInspectable CGFloat bottomInset;
@property IBInspectable CGFloat leftInset;
@property IBInspectable CGFloat rightInset;
@end
这个会放在yourlabel。m文件中:
IB_DESIGNABLE
@implementation YourLabel
#pragma mark - Super
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.topInset = 0;
self.bottomInset = 0;
self.leftInset = 0;
self.rightInset = 0;
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = UIEdgeInsetsMake(self.topInset, self.leftInset, self.bottomInset, self.rightInset);
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
- (CGSize)intrinsicContentSize {
CGSize size = [super intrinsicContentSize];
return CGSizeMake(size.width + self.leftInset + self.rightInset,
size.height + self.topInset + self.bottomInset);
}
@end
然后,在XIB文件或故事板中指定类后,您可以直接在Interface Builder中修改YourLabel嵌入,嵌入的默认值为零。
objective - c
基于Tai Le的回答,它在一个Interface Builder Designable中实现了这个特性,下面是Objective-C版本。
把这个放在YourLabel.h文件中:
@interface YourLabel : UILabel
@property IBInspectable CGFloat topInset;
@property IBInspectable CGFloat bottomInset;
@property IBInspectable CGFloat leftInset;
@property IBInspectable CGFloat rightInset;
@end
这个会放在yourlabel。m文件中:
IB_DESIGNABLE
@implementation YourLabel
#pragma mark - Super
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.topInset = 0;
self.bottomInset = 0;
self.leftInset = 0;
self.rightInset = 0;
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = UIEdgeInsetsMake(self.topInset, self.leftInset, self.bottomInset, self.rightInset);
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
- (CGSize)intrinsicContentSize {
CGSize size = [super intrinsicContentSize];
return CGSizeMake(size.width + self.leftInset + self.rightInset,
size.height + self.topInset + self.bottomInset);
}
@end
然后,在XIB文件或故事板中指定类后,您可以直接在Interface Builder中修改YourLabel嵌入,嵌入的默认值为零。