将子视图添加到UICollectionViewCell时出现意外行为

时间:2012-10-09 05:49:27

标签: objective-c ios uicollectionview uicollectionviewcell

我在向其添加子视图时遇到了一个奇怪的UICollectionViewCell问题,但仅限于某些情况。

以下是该方案:

我有一个“容器”视图,它符合具有嵌套视图的非常特定的协议(ADGControl),通常是UIKit控件子类,即MyCustomTextField:用于自定义控件的UITextField。

“容器”视图公开了一个名为“innerControlView”的属性,该属性包含对自定义控件的强引用,这是我尝试添加为单元格内容视图的子视图。

以下是代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   FormControlCollectionViewCell *cell = [self.formCollectionView dequeueReusableCellWithReuseIdentifier:@"formControlCell" forIndexPath:indexPath];
   NSArray *sectionContents = [_controlList objectAtIndex:[indexPath section]];

   // This works
   //UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 315.0f, 30.0f)];
   //textField.borderStyle = UITextBorderStyleLine;
   //[cell.controlView addSubview:textField];

   // This doesn't (see the behaviour in video clip)
   id <ADGControl> control = [sectionContents objectAtIndex:[indexPath row]]; // The container view I'm referring to
   [cell.contentView addSubview:(UIView *)[control innerControlView]]; // [control innerControlView] is the typical UIKit control subclass for custom controls. In this example it will be a UITextField

   return cell;
}

正如您在上面的代码注释中所看到的,每当我尝试直接添加一个UIKit控件(textField)时,它就可以正常工作。但是,只要我尝试添加自定义控件([control innerControlView],我就会看到视频片段中显示的意外行为:http://media.shinywhitebox.com/ryno-burger/ios-simulator-ios-simulator-ipad-ios-a

以上链接只是一段短短23秒的视频片段,可以更好地展示我所获得的“意外行为”。

如果有人能够指出我所犯的问题可能是什么,我将不胜感激。

由于

2 个答案:

答案 0 :(得分:3)

您可以在the documentation on UICollectionViewCells中阅读,不应将内容子视图添加到单元格本身,而应添加到contentView

而且,正如我之前在评论中所说的那样,您不应该在数据源中添加子视图,而应该在子类中添加子视图。您已经注意到未调用initWithFrame:,而是使用initWithCoder:

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Add your subviews here
        // self.contentView for content
        // self.backgroundView for the cell background
        // self.selectedBackgroundView for the selected cell background
    }
    return self;
}

答案 1 :(得分:0)

视图一次只能在一个超级视图中。如果它已经是容器视图的子视图,则不能将其添加为另一个视图(您的单元格)的子视图。

为什么您将视图用作模型对象的一部分并不是很清楚,但是您必须在将其添加到单元格之前更改该视图或从当前超视图中删除内部视图。