B3F484DD-ABF3-43EE-9D4B-5E3EB96D796E.png
使用xib布局銀行cell的時(shí)候锤灿,突然發(fā)現(xiàn)****的星號(hào)不能與銀行卡尾數(shù)垂直居中對(duì)齊挽拔,可能是由于*字體不和普通文字一樣居中顯示,廢話(huà)不多說(shuō)但校,直接上解決方案:
1.自定義UILabel, 添加edgeInsets屬性
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZGKBankCardLabel : UILabel
@property(nonatomic, assign) UIEdgeInsets edgeInsets;
@end
NS_ASSUME_NONNULL_END
2.重寫(xiě)UILabel的- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines 和 - (void)drawTextInRect:(CGRect)rect 方法
#import "ZGKBankCardLabel.h"
@implementation ZGKBankCardLabel
/** 返回UILabel中內(nèi)容所占的rect*/
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
UIEdgeInsets insets = self.edgeInsets;
CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)
limitedToNumberOfLines:numberOfLines];
rect.origin.x -= insets.left;
rect.origin.y -= insets.top;
rect.size.width += (insets.left + insets.right);
rect.size.height += (insets.top + insets.bottom);
return rect;
}
/** 在一定區(qū)域內(nèi)顯示出來(lái)UILabel的內(nèi)容*/
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
3.通過(guò)設(shè)置自定義cell中的自定義label的edgeInset屬性螃诅,來(lái)調(diào)整rect,使得*居中状囱,需要注意的是賦值edgeInsets后术裸,最好調(diào)用一下sizeToFit屬性。
@implementation ZGKMeBankCardCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
self.backgroud.layer.cornerRadius = 10;
self.bankCardNum.text = @"1314";
self.bankCardNum.font = [UIFont systemFontOfSize:20];
self.selectionStyle = UITableViewCellSelectionStyleNone;
// 下面兩句是重點(diǎn)代碼
self.firstStarLabel.edgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);//設(shè)置內(nèi)邊距
self.secondStarLabel.edgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);//設(shè)置內(nèi)邊距
self.thirdStarLabel.edgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);//設(shè)置內(nèi)邊距
[self.firstStarLabel sizeToFit];//重新計(jì)算尺寸亭枷,會(huì)執(zhí)行Label內(nèi)重寫(xiě)的方法
[self.secondStarLabel sizeToFit];//重新計(jì)算尺寸袭艺,會(huì)執(zhí)行Label內(nèi)重寫(xiě)的方法
[self.thirdStarLabel sizeToFit];//重新計(jì)算尺寸,會(huì)執(zhí)行Label內(nèi)重寫(xiě)的方法
}
調(diào)整以后的結(jié)果如下:
95D92E8A-8ED1-42C4-BF71-3A5B071EED49.png