引言
AutoLayout能快速地構(gòu)建頁(yè)面翁逞,提高開發(fā)效率总珠。相對(duì)于純手寫代碼屏鳍,新手能快速入門。然而局服,在實(shí)際開發(fā)過程中钓瞭,會(huì)遇到有些頁(yè)面如果單純使用AutoLayout布局會(huì)很困難,有種無從下手的感覺淫奔。這時(shí)就可以和代碼寫視圖的形式一起混合使用山涡。
實(shí)際案例
例如以下TableViewCell,由三部份組合而成唆迁。1和2的布局固定鸭丛。可以很方便使用AutoLayout以拖控件的形式實(shí)現(xiàn)唐责。但第2部份有以下難點(diǎn):
1.左邊的Label長(zhǎng)度不固定
2.右邊的視圖由Image和Label疊加成鳞溉。且Image的長(zhǎng)度隨Label變化。Label長(zhǎng)度也不固定
3.左邊和右邊長(zhǎng)度相加不能超過屏幕寬度鼠哥。如果超過熟菲,要保持右邊的長(zhǎng)度,左邊縮略
對(duì)于這種復(fù)雜的橫向多控件朴恳,長(zhǎng)度不統(tǒng)一的布局科盛,我暫時(shí)未有想到很好的方向。所以使用了手動(dòng)編寫視圖代碼的方法實(shí)現(xiàn)菜皂。
主要的代碼如下:
@interface ServiceItemListCell ()
@property (nonatomic, strong) UIView *titleView;
@end
- (void)setupTitleView {
_titleView = [[UIView alloc] initWithFrame:CGRectMake(87, 23, self.contentView.width - 87 - 10, 18)];
[self.contentView addSubview:_titleView];
NSString *saveString = [NSString stringWithFormat:@"減%ld",[_entity.originalPrice integerValue]-[_entity.price integerValue]];
CGSize labelSize = [saveString sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}];
UILabel *saveMoneyLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, labelSize.width, labelSize.height)];
saveMoneyLabel.text = saveString;
saveMoneyLabel.font = [UIFont systemFontOfSize:12];
saveMoneyLabel.textColor = [UIColor colorWithHexString:@"#3e82ff" alpha:1.0];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"service_price_subtract_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
imageView.width = saveMoneyLabel.width + 22 ;
CGSize nameSize= [_entity.name sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:18]}] ;
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, nameSize.width, 18)];
nameLabel.text = _entity.name;
nameLabel.font = [UIFont systemFontOfSize:18];
nameLabel.textColor = [UIColor colorWithHexString:@"#25292c" alpha:1.0];
if (nameLabel.width > _titleView.width - 10 - imageView.width) {
nameLabel.width = _titleView.width - 10 - imageView.width;
}
imageView.x = nameLabel.width + 10;
saveMoneyLabel.x = imageView.x + 12;
saveMoneyLabel.centerY = imageView.centerY;
[_titleView addSubview:nameLabel];
[_titleView addSubview:imageView];
[_titleView addSubview:saveMoneyLabel];
}
滾動(dòng)重復(fù)問題
在自定義Cell中手動(dòng)添加視圖后贞绵,滾動(dòng)列表,由于Cell重用機(jī)制恍飘,會(huì)出現(xiàn)重復(fù)添加的問題榨崩。在網(wǎng)上查閱相關(guān)的解決方案谴垫,發(fā)現(xiàn)最快的方法是重寫prepareForReuse方法,在重用時(shí)移除添加的視圖:
-(void)prepareForReuse {
[super prepareForReuse];
[_titleView removeFromSuperview];
}