2016-09-07 2 views
1

swift3에서 코딩하는 동안 컬렉션보기 셀을 재사용하기 위해 사용자 지정 프로토콜과 제네릭을 사용하려고했습니다. 나는이 재사용 세포의 표준 방법이라는 것을 알고" '호출 중'매개 변수에 대한 누락 된 인수

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TacoCell", for: indexPath) as? TacoCell { 

     cell.configureCell(taco: ds.tacoArray[indexPath.row]) 

     return cell 
    } 

    return UICollectionViewCell() 
} 

는하지만 매번 나는이 작업을 수행하려고 :

컴파일러는 내가 호출 '에 대한'매개 변수에 대한 "누락 인수를 가지고 불평

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as TacoCell 
    cell.configureCell(taco: ds.tacoArray[indexPath.row]) 
    return cell 
} 
나는 세포와로드 펜촉을 재사용에 대한 사용자 정의 확장이 forIndexPath "참고로

...

"...이 경우 매개 변수입니다. "

ReusableView 클래스

당신은있어
import UIKit 

protocol ReusableView: class { } 

extension ReusableView where Self: UIView { 

    static var reuseIdentifier: String { 
     return String.init(describing: self) 
    } 
} 

이것은 UICollectionView

import UIKit 

extension UICollectionView { 
    func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView { 

    let nib = UINib(nibName: T.nibName, bundle: nil) 
    register(nib, forCellWithReuseIdentifier: T.reuseIdentifier) 
} 


func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: NSIndexPath) -> T where T: ReusableView { 

    guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath as IndexPath) as? T else { 
     fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)") 
    } 

    return cell 
    } 
} 

extension UICollectionViewCell: ReusableView { } 
+0

당신이 (만) 'forIndexPath'를 사용 dequeueReusableCell''의 설명에 대한 링크를 제공 할 수 있을까요? 또한'forIndexPath'를'for'로 대체 해 보았습니까? – Evert

+0

Sorry @Evert ... UICollectionView의 확장을 만들었고,'forIndexPath' 인자를 가진 "재정의 된"'dequeueReusableCell' 메소드를 사용하고 있습니다. 내 가정은 그것이 확장으로 받아 들여 졌기 때문에 그것을 사용하여 셀을 재사용 할 수있었습니다. 위의 확장 코드도 포함했습니다. – CommittedEel

답변

2

문제에 대한 내 확장

import UIKit 

protocol NibLoadableView: class { } 

extension NibLoadableView where Self: UIView { 

    static var nibName: String { 
     return String.init(describing: self) 
    } 
} 

NibLoadableView 클래스는 것을 다음과 같이 코드입니다 Swift 3.0 코드와 함께 Swift 2.2 코드가 약간 섞여서 컴파일러가 혼란스러워지고 있습니다. n 꽤 일치하는 것이 없기 때문에 호출 할 메소드를 선택하려고합니다.

cellForItemAt 메서드는 컬렉션보기에서 IndexPath을 사용하여 자신의 dequeueReusableCell() 확장 메서드를 호출합니다. 그러나 사용자가 작성한 확장 메소드는 NSIndexPath을 수신 할 것으로 예상됩니다. 이는 약간 다른 것입니다.

이에 확장 방법을 개정하고 문제는 해결됩니다 :

func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView { 
+0

@TwoStraws! 감사합니다! 그것은 그것을 얻는 것처럼 보였다. – CommittedEel

관련 문제