【发布时间】:2015-06-23 16:16:10
【问题描述】:
我在为 UICollectionViewCells 使用 Xib 时遇到了一个奇怪的问题。问题是正在创建一个额外的视图,它似乎在一切之上,使我的手势和 IBActions 无用。
这是我的设置:
我有一个 UIViewController,里面有一个 UICollectionView。
在情节提要中,UICollectionView 有一个单元格,属于“MyCell”类,重用 id 为“cell”
在
cellForItemAtIndexPath中,我只返回[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]的结果。我还在numberOfItemsInSection中硬编码了 30 个项目。
就是这样。除此之外,我还有 MyCell.h、MyCell.m 和 MyCell.xib。
xib 包含一个 UIButton,其 Touch Up Inside 事件设置为调用
buttonPressedIBAction。视图本身设置为 MyCell 类,标签设置为 123(我们将在下面了解原因)。在 MyCell.m 中,我覆盖了
awakeAfterUsingCoder以返回[MyCell initView:self]。initView的定义在底部。但它基本上是从 Xib 加载视图。
就是这样。
当我运行应用程序时,会显示 30 个单元格,所有单元格都带有它们的按钮,但是当按下按钮时,什么也没有发生。经过大量的调查,我发现cell里面多了一个UIView,在button的上面,而且覆盖了整个东西。
如果我在 awakeAfterUsingCoder 中添加下面的 for 循环,那么按钮会再次起作用。
- (MyCell *)awakeAfterUsingCoder:(NSCoder *)aDecoder
{
MyCell *cell = [MyCell initView:self];
for(UIView *v in cell.subviews){
if(![v isKindOfClass:[UIButton class]]) [v removeFromSuperview];
}
return cell;
}
我的问题是:这种观点是什么,为什么会出现???即使我可以通过删除该视图来让一切正常工作,但感觉就像是一个 hack。
谢谢!如果需要,我可以回答任何其他问题。
+ (id)initView:(UIView *)viewToInit
{
UIView *viewToReturn;
if(viewToInit.tag != 123){
//If we're in the storyboard codepath
//Initialize from the xib.
//If the code below is failing, we probably forgot the 666 tag :/
viewToReturn = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([viewToInit class])
owner:nil
options:nil] firstObject];
//copy frame, autoresizing, and layour items.
viewToReturn.frame = viewToInit.frame;
viewToReturn.autoresizingMask = viewToInit.autoresizingMask;
viewToReturn.translatesAutoresizingMaskIntoConstraints = viewToInit.translatesAutoresizingMaskIntoConstraints;
for (NSLayoutConstraint *constraint in viewToInit.constraints){
id firstItem = constraint.firstItem;
if (firstItem == viewToInit){
firstItem = viewToReturn;
}
id secondItem = constraint.secondItem;
if (secondItem == viewToInit){
secondItem = viewToReturn;
}
[viewToReturn addConstraint:[NSLayoutConstraint constraintWithItem:firstItem
attribute:constraint.firstAttribute
relatedBy:constraint.relation
toItem:secondItem
attribute:constraint.secondAttribute
multiplier:constraint.multiplier
constant:constraint.constant]];
}
}else{
//otherwise do nothing and just return what was passed in
viewToReturn = viewToInit;
}
return viewToReturn;
}
【问题讨论】:
标签: ios objective-c uicollectionview xib uicollectionviewcell