美文网首页ios 控件iOS Developer ios零碎记录
解决往可重用Cell中手动添加View时重复显示问题

解决往可重用Cell中手动添加View时重复显示问题

作者: JamesCaiLee | 来源:发表于2016-03-23 11:53 被阅读371次

    引言

    AutoLayout能快速地构建页面,提高开发效率。相对于纯手写代码,新手能快速入门。然而,在实际开发过程中,会遇到有些页面如果单纯使用AutoLayout布局会很困难,有种无从下手的感觉。这时就可以和代码写视图的形式一起混合使用。

    实际案例

    例如以下TableViewCell,由三部份组合而成。1和2的布局固定。可以很方便使用AutoLayout以拖控件的形式实现。但第2部份有以下难点:

    1.左边的Label长度不固定

    2.右边的视图由Image和Label叠加成。且Image的长度随Label变化。Label长度也不固定

    3.左边和右边长度相加不能超过屏幕宽度。如果超过,要保持右边的长度,左边缩略

    对于这种复杂的横向多控件,长度不统一的布局,我暂时未有想到很好的方向。所以使用了手动编写视图代码的方法实现。

    image

    主要的代码如下:

    @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];
    

    }

    滚动重复问题

    在自定义Cell中手动添加视图后,滚动列表,由于Cell重用机制,会出现重复添加的问题。在网上查阅相关的解决方案,发现最快的方法是重写prepareForReuse方法,在重用时移除添加的视图:

    -(void)prepareForReuse {
    [super prepareForReuse];
    [_titleView removeFromSuperview];
    }
    
    image

    相关文章

      网友评论

        本文标题:解决往可重用Cell中手动添加View时重复显示问题

        本文链接:https://www.haomeiwen.com/subject/nqillttx.html