UITableViewCell中cell重用机制致使内容重复的方法

   UITableView继承自UIScrollview,是苹果为咱们封装好的一个基于scroll的控件。上面主要是一个个的UITableViewCell,可让UITableViewCell响应一些点击事件,也能够在UITableViewCell中加入UITextField或者UITextView等子视图,使得能够在cell上进行文字编辑。ide

   UITableView中的cell能够有不少,通常会经过重用cell来达到节省内存的目的:经过为每一个cell指定一个重用标识符(reuseIdentifier),即指定了单元格的种类,当cell滚出屏幕时,会将滚出屏幕的单元格放入重用的queue中,当某个未在屏幕上的单元格要显示的时候,就从这个queue中取出单元格进行重用。spa

   但对于多变的自定义cell,有时这种重用机制会出错。好比,当一个cell含有一个UITextField的子类并被放在重用queue中以待重用,这时若是一个未包含任何子视图的cell要显示在屏幕上,就会取出并使用这个重用的cell显示在无任何子视图的cell中,这时候就会出错。code

   解决方法:orm

方法一:blog

  将得到cell的方法从- (UITableViewCell*)dequeueReusableCellWithIdentifier:(NSString*)identifier 换为-(UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath继承

  重用机制调用的就是dequeueReusableCellWithIdentifier这个方法,方法的意思就是“出列可重用的cell”,于是只要将它换为cellForRowAtIndexPath(只从要更新的cell的那一行取出cell),就能够不使用重用机制,于是问题就能够获得解决,虽然可能会浪费一些空间。队列

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //改成如下的方法 //根据indexPath准确地取出一行,而不是从cell重用队列中取出
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } //...其余代码
}

方法二: 经过为每一个cell指定不一样的重用标识符(reuseIdentifier)来解决事件

  重用机制是根据相同的标识符来重用cell的,标识符不一样的cell不能彼此重用。因而咱们将每一个cell的标识符都设置为不一样,就能够避免不一样cell重用的问题了。内存

  

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //以indexPath来惟一肯定cell
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", [indexPath section], [indexPath row]]; //出列可重用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } //...其余代码
}

方法三: 删除重用cell的全部子视图rem

  这个方法是经过删除重用的cell的全部子视图,从而获得一个没有特殊格式的cell,供其余cell重用。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; //出列可重用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } else { //删除cell的全部子视图
        while ([cell.contentView.subviews lastObject] != nil) { [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview]; } } //...其余代码
}

方法三我试着好像有些问题,具体怎么弄正在研究,

相关文章
相关标签/搜索