-1

사용자 지정 UICollectionViewCell 클래스를 사용하여 UICollectionView를 설정합니다.문자열이 사용자 지정 클래스에 전달 될 때 UICollectionViewCell의 레이블 텍스트 설정이 작동하지 않습니다.

UICollectionViewDelegate에 지정된 함수를 사용하여 각 셀에 텍스트로 채워진 레이블을 얻을 수있었습니다.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "keypadButton", for: indexPath) as! KeypadButtonCollectionViewCell 
    cell.awakeFromNib() 
    return cell 
} 


func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { 
    let button = cell as! KeypadButtonCollectionViewCell 

    //Assigning like this works 
    button.buttonLabel.text = tempScale[indexPath.row] 
} 

그러나,

나는 처음에 (아래로)을 KeypadButtonCollectionViewCell 클래스에서 buttonText 클래스 변수와 다르게 설정하고

class KeypadButtonCollectionViewCell: UICollectionViewCell { 


    var buttonLabel: UILabel! 
    var buttonText: String! 

    override func awakeFromNib() { 
     buttonLabel = UILabel.init(frame: contentView.frame) 
     buttonLabel.font = UIFont.init(name: "HelveticaNeue-Ultralight", size: 20) 
     buttonLabel.textColor = UIColor.black 
     buttonLabel.textAlignment = NSTextAlignment.center 

     buttonLabel.text = buttonText //Assigning here didn't work 

     contentView.layer.borderColor = UIColor.init(red: 37/255, green: 37/255, blue: 37/255, alpha: 1).cgColor 
     contentView.layer.borderWidth = 4 
     contentView.addSubview(buttonLabel) 

    } 

} 


//---------In the view controller-------- 

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { 
    let button = cell as! KeypadButtonCollectionViewCell 

    //Setting class var string here to be set as label.text not working 
    button.labelText = tempScale[indexPath.row] 
} 

그것이 내가 여기에 무엇을 오해하고있다 (또한 아래) willDisplay 함수에서 그 변수를 설정했다 ? wakeFromNib() 메서드에서 레이블 텍스트를 설정하기 위해 할당 된 클래스 변수를 사용하도록 설정하는 것이 좋지 않지만 레이블 텍스트를 직접 설정할 때 효과가있는 이유는 무엇입니까?

처음에 언급했듯이, 나는 이것을하기위한 작업 방법이있다. 나는 이것을 학계에 관심이 있고 OOP 프로그래밍을 더 잘 이해하고있다.

답변

1

awakeFromNibviewsubviews이 할당되고 초기화 된 후에 자동으로 호출되므로 명시 적으로 호출하지 마십시오. 따라서 cell.awakeFromNib() 줄을 제거하십시오. awakeFromNib이 당신의 buttonText 문자열이라고 귀하의 경우에는

nil하고 문자열 값 buttonText하지만 awakeFromNib을 설정하는 willDisplay cell 메서드 호출이 이미 전에 호출 될 때 그렇게 buttonText을 설정하여 label의 값이 업데이트되지 않습니다이다. 문서에서

awakeFromNib에 :

펜촉 로딩 인프라가 펜촉 아카이브에서 다시 각 객체에로 awakeFromNib 메시지를 전송, 아카이브에있는 모든 개체가로드 및 초기화되었지만 후에 만. 개체가 awakeFromNib 메시지를 받으면 모든 콘센트 및 작업 연결이 이미 설정되어 있음을 보증합니다.

첫 번째 접근하고있는 방법은 레이블의 텍스트에 직접 배열 요소를 설정하여 완벽하지만 당신은 문자열 값 buttonText을 설정하려는 경우 당신은 당신 buttonText의 관찰 특성 didSet 같이 갈 수 이 방법. 당신이 willDisplay cellbuttonText 값을 설정할 때

var buttonText: String = "" { 
    didSet { 
     buttonLabel.text = buttonText 
    } 
} 

는 이제 때문에 당신의 buttonTextdidSet의 세포의 라벨의 값을 업데이트합니다.