didHighlightItemAtIndexPath 没有按预期工作

didHighlightItemAtIndexPath not working as expected

关于 UICollectionViewDelegate 我正在使用 didHighlightItemAtIndexPath 以及 didSelectItemAtIndexPath

didSelectItemAtIndexPath 正在按预期工作。也就是说,当我点击遥控器时,这段代码 运行s.

问题是 didHighlightItemAtIndexPath 也会在点击时 运行ning,顾名思义,此块只会 运行 高亮显示。我错过了什么吗?

各自的区块:

func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
    let node: XMLIndexer = self.xml!["ArrayOfVideo"]["Video"][indexPath.row]

    let title = (node["Title"].element?.text)!
    let date = (node["Date"].element?.text)!(node["SpeakerOrganization"].element?.text)!

    self._title.text = title
    self._date.text = date
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let node: XMLIndexer = self.xml!["ArrayOfVideo"]["Video"][indexPath.row]

    let videoUrl = (node["VideoURL"].element?.text)!

    self.playVideoByUrlString(videoUrl)
}

补充说明

对于 UICollectionViewCell 我通过添加以下内容在单元格图像上获得视差感:

// self is a UICollectionViewCell
// self.imageView is a UIImageView

self.imageView.adjustsImageWhenAncestorFocused = true
self.imageView.clipsToBounds = false

解决方案

覆盖 UICollectionView 委托

中的 shouldUpdateFocusInContext

方法 didHighlightItemAtIndexPathdidSelectItemAtIndexPath 之前调用,因为 UICollectionView 安排。每次您触摸单元格时,它都会在 select 之前突出显示(我假设是出于视觉目的)。你可以通过这个例子看到它:

func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
    print("highlight")
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("select")
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
    let imageView = UIImageView(frame: CGRect(origin: CGPointZero, size: cell.frame.size))
    imageView.image = imageFromColor(UIColor.redColor(), size: cell.frame.size)
    imageView.highlightedImage = imageFromColor(UIColor.blueColor(), size: cell.frame.size)
    cell.addSubview(imageView)
    return cell
}

func imageFromColor(color: UIColor, size: CGSize) -> UIImage {
    let rect = CGRectMake(0, 0, size.width, size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

当我触摸单元格输出时

highlight 
select

如果您想让单元格突出显示或 selected,请只查看 UICollectionViewDelegate's 方法 shouldHighlightItemAtIndexPathshouldSelectItemAtIndexPath。您可以通过检查 shouldSelectItemAtIndexPath.

中的 indexPath 来防止 selecting 突出显示的单元格