2017-01-15 2 views
0

2 개의 레이블과 버튼이있는 사용자 지정 UITableViewCell이 있습니다. 세포는 자신의 클래스가 : 테이블 뷰를 포함하는 뷰 컨트롤러 내부표 셀에서 정보를 검색 하시겠습니까?

class personTableCell: UITableViewCell { 
    @IBOutlet weak var nameLabel: UILabel! 
    @IBOutlet weak var emailLabel: UILabel! 

    @IBAction func inviteButtonPressed(_ sender: Any) { 
     self.accessoryType = .checkmark 
    } 
} 

을,이 방법으로 테이블에 셀을 추가 :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "person", for: indexPath) as? personTableCell 
     cell?.nameLabel.text = results[indexPath.row].name 
     cell?.emailLabel.text = results[indexPath.row].email 
     return cell! 
} 

는 사용자가 내부의 버튼을 누르면 셀에 @IBAction func inviteButtonPressed을 호출하면 셀의 레이블 텍스트를 테이블과 동일한보기 컨트롤러에서 초기화 된 배열에 추가하려고합니다.

@IBAction func inviteButtonPressed이 테이블의보기 컨트롤러로 별도의 파일에 있다면 어떻게해야합니까?

+0

는 관련되지 않음 : 조류에 대한 너무 많은 질문 느낌표. 진지하게 : 테이블 뷰 셀 (뷰)에서 정보를 얻지 말고 데이터 소스 배열 (모델)에서 얻으십시오 – vadian

+0

@vadian 정교하세요? – MarksCode

+0

'dequeueReusableCell (withIdentifier : indexPath)'는 비표준 셀을 반환합니다. 그것은 선택적 캐스팅에 매우 어리 석다. 셀은 인터페이스 빌더에서 분명히 생성되므로 분명히 존재합니다. – vadian

답변

1

위임을 사용하는 것이 해결책 중 하나라고 생각합니다. 의 ViewController 클래스에서

@objc protocol PersonTableViewCellDelegate { 
    func personTableViewCellInviteButtonPressed(cell: PersonTableViewCell) 
} 

class PersonTableViewCell: UITableViewCell { 

    weak var delegate: PersonTableViewCellDelegate? 

    @IBAction func inviteButtonPressed(_ sender: Any) { 
     delegate?.personTableViewCellInviteButtonPressed(cell: self) 
    } 

} 

TableViewCell 클래스에서

class TableViewController: UITableViewController, PersonTableViewCellDelegate { 

    var results: [Person] = [] 
    var invited: [Person] = [] 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "person", for: indexPath) as! PersonTableViewCell 
     cell.nameLabel.text = results[indexPath.row].name 
     cell.emailLabel.text = results[indexPath.row].email 
     cell.delegate = self 
     return cell 
    } 

    func personTableViewCellInviteButtonPressed(cell: PersonTableViewCell) { 
     guard let indexPath = tableView.indexPath(for: cell) else { 
      return 
     } 
     let person = results[indexPath.row] 
     invited.append(person) 
    } 

} 
관련 문제