2017-01-17 8 views
1

주위를 읽었으므로 검색이 완전히 끔찍한 경우를 제외하고는 복제본으로 두드리지 마십시오. 기본적으로작은 UITableView, dequeReuseableCell을 제거하십시오

그러나 나는 그들이 내가 동적 인 방법보다는 정적 인 방법을 사용하고 있는데 이유는 (튜플에 그와 관련된 인덱스가 할 작은 테이블 (5 고정 행)이있다.

선수 목표 . 나는이 세포가 채워하기 위해 펜촉을 사용하고 있지 않다 주위의 세포를 교환하는 것입니다,이 방법.

이제
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cellID = "Cell" 
    let customCell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! DefinitionMatchTableViewCell 

    customCell.background.layer.borderWidth = CGFloat(2.0) 

    if tableView == nameTableLeft{ 
     customCell.textToDislay!.text = nameList[indexPath.row].0 
     customCell.background.layer.borderColor = UIColor(red: 255/255, green: 192/255, blue: 1/255, alpha: 1.0).cgColor 
     let cellIDFromTuple = nameList[indexPath.row].1 
     customCell.tag = cellIDFromTuple 
    } 

    if tableView == definitionTableRight{ 
     customCell.textToDislay!.text = definitionList[indexPath.row].0 
     customCell.background.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.2).cgColor 
     let cellIDFromTupleForDefinition = definitionList[indexPath.row].1 
     customCell.tag = cellIDFromTupleForDefinition 
    } 

    customCell.background.backgroundColor = UIColor.clear 
    customCell.backgroundColor = UIColor.clear 
    return customCell 
} 

문제 아이폰 SE에 5 개 세포가 초래되는 맞지 않을 수 있다는 것입니다 값이 일치하는지 검사 할 때 참조 ID가 손실되는 위쪽 또는 아래쪽 셀.이 경우 게임을 완료 할 수 없으므로 인덱스 값을 테이블에 채울 수있는 방법이 필요합니다. e는 각 문자열과 연관되어 있지만 테이블은 셀을 재사용하지 않지만 메모리에 남아 있습니다.

내가 생각할 수있는 유일한 방법은 정적 테이블에 데이터를 쓰는 것입니다. 그런 다음 각 셀에 문자열과 관련되어있는 보이지 않는 인덱스를 제공하는 것입니다. 그러나 나는 오히려 그것을 동적으로 할 것이다.

이러한 셀의 상태를 유지하기위한 조언은 크게 감사하겠습니다. 감사!

편집 여기에 1

내가 테이블에 내 인덱스 값을 기준으로 답변을 확인하는 방법입니다. 나는 어떤

for index in nameTableLeft.indexPathsForVisibleRows!{ 
      let leftCell = nameTableLeft.cellForRow(at: index) as? DefinitionMatchTableViewCell 
      let rightCell = definitionTableRight.cellForRow(at: index) as? DefinitionMatchTableViewCell 

if nameTableLeft.cellForRow(at: index)?.tag == definitionTableRight.cellForRow(at: index)?.tag{ 
       leftCell?.background.layer.borderColor = UIColor.green.cgColor 
       rightCell?.background.layer.borderColor = UIColor.green.cgColor 
       counter += 1 
      }else{ 
       leftCell?.background.layer.borderColor = UIColor.red.cgColor 
       rightCell?.background.layer.borderColor = UIColor.red.cgColor 
      } 
     } 

볼 수 없습니다 당신이 그때 값이 태그를 일치 확인 볼 수 있듯이 문제가 .indexPathsForVisibleRows에서 오는 상상한다. 그러나 나는 뭔가 다른 것을 사용한다면이 개념에 어려움을 겪고있다.

내 모델 2 개

덕분에 내 대답은 확인이를 추가하기로 결정했던 답변에 도움을

var nameList : [(String, Int)] = [("Trojan", 0), 
            ("Virus", 1), 
            ("Spyware", 2), 
            ("Ransomware", 3), 
            ("Leakware", 4)] 
var definitionList : [(String, Int)] = [("Attaches onto another program. Replicates itself. Something loaded onto your device without your knowledge. Continues to spread", 0), 
             ("When malware is disguised as something else. Usually an e-mail attachment", 1), 
             ("Tracks a user's actions, this includes login details, internet habits and any secure accounts", 2), 
             ("Locks a device or encrypts files and demands money to unlock it", 3), 
             ("Threatens to distribute your information", 4)] 

편집.

for answerIndex in 0...4{ 
      if definitionList[answerIndex].1 == nameList[answerIndex].1{ 
       print("MATCH") 
       counter += 1 
      }else{ 
       print("NO MATCH") 
      } 
     } 

나는 정의와 이름 목록을 함께 시작합니다. 그런 다음 테이블의 전체 길이를 기반으로 터플에 배치 된 두 인덱스를 모두 보려고합니다. 불행하게도 나는 튜플을 반복 할 수 없다는 마법의 숫자에 의지해야만했다.

그래서이 작은 루프는 내 튜플에 인덱스가 정렬되어 있는지를 결정합니다. 그렇지 않으면 올바른 것이 아닙니다. 도와 주신 모든 분들께 다시 한번 감사드립니다.

답변

3

나는 또한 비슷한 문제를 해결했다. 내 충고는 세포를 계속 재사용하는 것입니다. 각 셀에 해당하는 데이터를 별도의 모델 클래스에 외부에 저장하십시오. 그런 다음이를 가변 배열에 저장하십시오. 셀을 섞으면 변경 가능한 배열의 데이터를 임의로 섞습니다.

다음과 같은 방법으로 수행 할 수 있습니다.

model 클래스

class model: NSObject { 

    var name: String = "" 
    var definition: String = "" 
    var type: String = "" 

    required init(name: String, definition: String, type: String) { 
     super.init() 

     self.name = name 
     self.definition = definition 
     self.type = type 
    } 
} 

사용자 정의 UITableViewCell - 셀 등록 다른 레이아웃

class CustomTableViewCell: UITableViewCell { 

    var nameLabel: UILabel = UILabel() 
    var definitionLabel: UILabel = UILabel() 

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)  
    { 
     super.init(style: style, reuseIdentifier: reuseIdentifier) 

     nameLabel.textColor = UIColor.black 
     nameLabel.font = UIFont.systemFont(ofSize: 15) 
     nameLabel.textAlignment = NSTextAlignment.left 
     self.contentView.addSubview(nameLabel) 

     definitionLabel.textColor = UIColor.brown 
     definitionLabel.font = UIFont.systemFont(ofSize: 15) 
     definitionLabel.textAlignment = NSTextAlignment.right 
     self.contentView.addSubview(definitionLabel) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    override func layoutSubviews() { 
     super.layoutSubviews() 

     nameLabel.frame = CGRect(x: 10, y: 10, width: self.contentView.frame.size.width - 20, height: self.contentView.frame.size.height - 20) 
     definitionLabel.frame = CGRect(x: 10, y: 10, width: self.contentView.frame.size.width - 20, height: self.contentView.frame.size.height - 20) 
    } 

    override func setSelected(_ selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 

    } 

} 

에 대한 사소한 예 :

self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") 

모델에 따라 CustomTableViewCell 사용을 :

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) 

    // Configure the cell... 
    if model.type == "name" { 
     cell.nameLabel.text = model.name 
     cell.definitionLabel.isHidden = true 
    }else if model.type == "definition" { 
     cell.definitionLabel.text = model.definition 
     cell.nameLabel.isHidden = true 
    } 

    return cell 
} 

움직이는 세포 부분 :

let mutableArray:[model] = [model1, model2, model3, model4, model5] // model class holds data for each cell 

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { 
    let source = sourceIndexPath.row; 
    let destination = destinationIndexPath.row; 

    let sourceModel = mutableArray[source] 
    let destinationModel = mutableArray[destination] 

    mutableArray[source] = destinationModel 
    mutableArray[destination] = sourceModel 
} 

는이 구현에 대한 의심이있는 경우 의견을 주시기 바랍니다. 편집이 더 나은 :)

편집을하는 것이 좋습니다 주시기 바랍니다 : - 행을 따라 이동할 때 그것의 인덱스 위치에 튜플의

경우에도 값을 변경할 수 있습니다.

var nameList : [(String, Int)] = [("Trojan", 0), 
            ("Virus", 1), 
            ("Spyware", 2), 
            ("Ransomware", 3), 
            ("Leakware", 4)] 

let source = sourceIndexPath.row 
let destination = destinationIndexPath.row 

var sourceTuple: (String, Int) = nameList[source] 
var destinationTuple: (String, Int) = nameList[destination] 

sourceTuple.1 = destination 
destinationTuple.1 = source 

nameList[destination] = sourceTuple 
nameList[source] = destinationTuple 
+0

안녕하세요, 감사합니다. 나는 이것을보고 있었다. 따라서 소스와 대상은 단지 정적입니다. 기본적으로이 방법으로 데이터를 교환하고있는 것을 볼 수 있습니다. 그러면 어떻게 세포를 만들었습니까? 정적 기반? 시간 내 주셔서 감사합니다 :) – CardDeath

+0

죄송합니다. 나는 그 대답을 편집했다. 'source'와'destination'은'sourceIndexPath.row'와'destinationIndexPath.row'에 해당합니다. 셀은 프로그래밍 방식으로 생성 된 프로토 타입 셀입니다. 우리가 할 수있는 다른 레이아웃을 가진 세포가 필요하다면. 모델은 특정 셀에 대한 모든 데이터를 보유하고 있기 때문입니다. CustomCell과'cellForRowAt' 메소드에 예제를 추가할까요? – KrishnaCA

+0

당신이 친절하면 아주 좋을 것입니다. 나는 정말로 UITableView의 시스템과 싸워서는 안된다는 것을 알고 있지만 그것은 나에게 논리적으로 보인다. 시간 내 주셔서 대단히 감사합니다. – CardDeath

2

먼저 셀을 재사용하고 셀에 상태를 저장하지 않아야합니다. 그러나 빠른 대답을 원하면 모든 셀마다 다른 재사용 식별자를 설정하십시오.

+0

그래서 다른 재사용 식별자에서 동일한 프로토 타입 셀을 5 개 만들 것을 제안합니까? 그런 다음 코드 내부에서 어떻게 호출합니까? 시간 내 주셔서 감사합니다 – CardDeath

+0

당신이 펜촉을 사용하지 않는다고 말한 줄 알았는데. [self.tableView registerClass : [UITableViewCell class] forCellReuseIdentifier : @ "cell1"]와 같은 재사용 식별자에 대한 클래스를 등록 할 수 있으며 cell2 등에 대해서도 동일하게 적용 할 수 있습니다. –

+0

정확합니다. 펜촉을 사용하고 있지 않습니다. 고마워요 존 내가 그걸 시도 해보고 내가 어떻게 시작하는지 알려줄 께! – CardDeath