我在使用 Xib 作为 UICollectionViewCells 时遇到了一个奇怪的问题。问题是正在创建一个附加 View ,它似乎位于所有内容之上,使我的手势和 IBActions 毫无用处。
这是我的设置:
我有一个 UIViewController,其中有一个 UICollectionView。
在 Storyboard中,UICollectionView 有一个单元格,属于“MyCell”类,重用 ID 为“cell”
在
cellForItemAtIndexPath
中,我只返回[collectionView dequeueReusableCellWithReuseIdentifier:@"cell"forIndexPath:indexPath]
的结果。我还在numberOfItemsInSection
中硬编码了 30 个项目。
就是这样。除此之外,我还有 MyCell.h、MyCell.m 和 MyCell.xib。
xib 包含一个 UIButton,其 Touch Up Inside 事件设置为调用
buttonPressed
IBAction。 View 本身设置为 MyCell 类,标记设置为 123(我们将在下面了解原因)。在 MyCell.m 中,我重写了
awakeAfterUsingCoder
以返回[MyCell initView:self]
。initView
的定义位于底部。但它基本上从 Xib 加载 View 。
就是这样。
当我运行应用程序时,会显示 30 个单元格,全部带有按钮,但是当按下按钮时,没有任何反应。经过大量调查后,我发现单元格内添加了一个额外的 UIView,位于按钮顶部,并且覆盖了整个内容。
如果我在 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;
}
我的问题是:那个 View 是什么,为什么它在那里???尽管我可以通过删除该 View 来让一切正常工作,但感觉就像是黑客攻击。
谢谢!如果有必要,我可以回答任何其他问题。
+ (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;
}
最佳答案
我自己也遇到过这个问题,答案就在单元 nib 文件中。如果您创建了一个 Nib 并使用包含为单元格的库存 UIView,那么这就是您的问题所在。该 UIView 需要立即删除并替换为新拖动的 UICollectionViewCell。这将是您的单元格,您可以将 View 添加到您的心中内容,而不会出现其他问题。
关于ios - 附加 View 插入到从 Xib 加载的 UICollectionView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008151/