ios - UITableViewCell 和 UILabel

标签 ios uitableview uilabel

我正在添加两个自定义 UILabel转至我的 UITableView 的一部分这样:

//in .h file:
NSArray *listaopzioni;
@property (nonatomic, retain) NSArray *listaopzioni;

//in .m file:
self.listaopzioni = [[NSArray arrayWithObjects:@"Strumenti",@"Help & Credits", nil] retain];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    if ([indexPath section]==0) {

        cell.accessoryType = UITableViewCellAccessoryNone;

        UILabel *slogan= [[UILabel alloc] initWithFrame:CGRectMake(0,0,cell.frame.size.width,cell.frame.size.height)];
        slogan.text=[listaopzioni objectAtIndex:indexPath.row];
        slogan.textAlignment=UITextAlignmentCenter;
        slogan.font= [UIFont boldSystemFontOfSize:20];
        slogan.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:slogan];
        [slogan release];


    } 
}

一切都很完美,但是当我在表格 View 中上下滑动时(试图覆盖 UINavigationBar 下方的单元格),我得到了一个奇怪的效果:文本重叠只是使每个字母变厚。

怎么了?

最佳答案

方法cellForRowAtIndexPath每次单元格变得可见时都会调用。
这就是每次滚动时它都会创建标签的原因。
解决方案是在创建单元格时放置标签创建:

 if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    if ([indexPath section]==0) {

    cell.accessoryType = UITableViewCellAccessoryNone;

    UILabel *slogan= [[UILabel alloc] initWithFrame:CGRectMake(0,0,cell.frame.size.width,cell.frame.size.height)];
    slogan.text=[listaopzioni objectAtIndex:indexPath.row];
    slogan.textAlignment=UITextAlignmentCenter;
    slogan.font= [UIFont boldSystemFontOfSize:20];
    slogan.backgroundColor=[UIColor clearColor];
    [cell.contentView addSubview:slogan];
    [slogan release];


   } 
}

关于ios - UITableViewCell 和 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15176928/

相关文章:

ios - UISearchController 中的取消按钮导致 SearchBar 故障

iphone - 更改NSDate的时间?

ios - 随机化 Firebase 存储中的图像

iOS 10 - UITableViewController 在加载时滚动到底部

iphone - TableView 重新加载数据未调用 cellForRowAtIndexPath

ios - UIlabel 问题 : Keep the string value after app is closed?

ios - 像素碰撞检测?

带有不透明标题的 UITableViewStylePlain

ios - 当没有 self.view 时,如何找到 UIView...?

iphone - 在 Xcode 的 UILabel 上编写印地语