gpt4 book ai didi

iOS,UICollectionViewCell 格式错误的 UILabel

转载 作者:行者123 更新时间:2023-11-28 21:51:06 24 4
gpt4 key购买 nike

我有一个显示电话号码 block 的 UICollectionViewController(见图)。当 View 加载时,它们看起来都很好,但是当我开始滚动、更改旋转或执行更改数据来源的(可变)数组的搜索功能时,我看到这些格式错误的标签。我确实认为它可能是 iOS 模拟器,但是从它的角度来看,它似乎是 UICollectionViewCells 的定位问题。

enter image description here

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

cell.backgroundColor = [UIColor grayColor];
cell.layer.cornerRadius = 5;
[cell setClipsToBounds: YES];

CGRect cellBound = CGRectMake(25, 12.5, 150, 12.5); // x, y, w, h
UILabel *title = [[UILabel alloc] initWithFrame:cellBound];

NSString *number = [[searchNumbers objectAtIndex:indexPath.row] valueForKey:@"number"];
number = [number stringByReplacingOccurrencesOfString:@"+44" withString: @"0"];
title.text = number;

[cell addSubview:title];
return cell;
}

需要注意的是我使用的是UICollectionViewFlowLayout

最佳答案

正如@Woodstock 提到的,这是由于“过度添加”UILabel 对象到您的单元格。

而不是他的解决方案,它仍然将 UILabel 添加到 -collectionView:cellForRowAtIndexPath: 中的单元格,更好的 MVC 解决方案是这样的:

// A UICollectionViewCell subclass
// Make sure to pick the correct "init" function for your use case
- (instancetype)init... {
self = [super init...];
if (self != nil) {
[self setupCell];
}
return self;
}
- (void)setupCell {
self.backgroundColor = [UIColor grayColor];
self.clipsToBounds = YES;
self.layer.cornerRadius = 5;
CGRect cellBound = CGRectMake(25, 12.5, 150, 12.5); // x, y, w, h
// Assumes you've set up a UILabel property
self.titleLabel = [[UILabel alloc] initWithFrame:cellBound];
[cell addSubview:self.titleLabel];
}
- (void)configureWithNumber:(NSString *)number {
number = [number stringByReplacingOccurrencesOfString:@"+44" withString: @"0"];
self.titleLabel.text = number;
}

// In your UICollectionViewDataSource/Delegate implementation
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
NSString *number = [[searchNumbers objectAtIndex:indexPath.row] valueForKey:@"number"];
[cell configureWithNumber:number];
return cell;
}

基本上,您希望在最初设置单元格时设置和添加 View 。之后,您应该传入数据值/对象并配置单元格。如果您有需要不同控件的单元格(2 个标签与 1 个标签等),则创建多个子类。通过这种方式,您可以封装您的类以获得更清晰的代码和更好的重用。

关于iOS,UICollectionViewCell 格式错误的 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28300044/

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