gpt4 book ai didi

iphone - UITableView 单元格中的左+右对齐文本,当表格滚动时中断

转载 作者:搜寻专家 更新时间:2023-10-30 19:46:48 24 4
gpt4 key购买 nike

我的目标是在同一个单元格中显示 2 个字符串,其中一个左对齐,另一个右对齐。我附加的代码只是在表格 View 中执行此操作,但是当您向上/向下滚动时它会中断。我需要它在可以滚动的表格中工作。有人提到使用 CustomUITableViewCells 而不是我当前的方法,谁能给我举个例子?

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

UILabel *rank = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 100, 20];
[rank setTag:5];
[cell.contentView addSubview:rank];
[rank release];

UILabel *item = [[UILabel alloc] initWithFrame:CGRectMake(110, 5, 220, 20];
[item setTextAlignment:UITextAlignmentRight];
[item setTag:6];
[cell.contentView addSubview:item];
[item release];
}

UILabel *rank = (UILabel *)[cell viewWithTag:5];
UILabel *item = (UILabel *)[cell viewWithTag:6];

rank.text = @"leftside";
item.text = @"rightside";
}

Any ideas and thoughts greatly appricated, thanks for lookin

最佳答案

这个问题是因为dequeueReusableCellWithIdentifier。当单元格被重新使用时,当您上下滚动时,它会导致重大问题,因为标签作为 subview 添加到单元格并且它们没有单元格的属性。但是,如果您使用 cell.textLabel 作为您的标签,它不会导致您现在面临的问题,但您不能添加多个标签。

对此您有两种解决方案。

  1. 在您的情况下,您需要停止对每个单元格使用相同的 cellIdentifier 并为每个单元格使用不同的标识符,这样它们就不会被重复使用。如果 tableView 中的行数非常少,这会很有用,否则效率会很低。

  2. 更好的解决方案是子类 UITableViewCell 并在它的代码中添加这两个标签,然后将 UITableViewCell 与 dequeueReusableCellWithIdentifier。这只是少量工作,您可以重复使用单元格。如果您的 tableview 中有大量行,这将非常有用。

    通过THIS TUTORIAL了解如何使用 2 个标签子类化 UITableViewCell

    您需要使用方法 - (void)layoutSubviews 并将这些标签添加到您的自定义 UITableViewCell 子类。

请记住在加载 tableView 时引用此 customUITableViewCell 而不是默认的 uitableviewcell。您的 UILabels 不会再乱七八糟了。

Another reference .

关于iphone - UITableView 单元格中的左+右对齐文本,当表格滚动时中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6964483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com