iOS, Swift
Swift ) UIButton in Cell not working - EEYatHo iOS
EEYatHo
2021. 3. 22. 18:11
class MyCell: UITableViewCell {
...
func initFunc() {
...
myButton.addTarget(self, action: #selector(myFunc(_:)), for: .touchUpInside)
...
}
@objc myFunc(sender: UIButton) {
...
}
...
}
이런식으로 셀 안에서 addTarget으로 셀 안에 있는 @objc func을 연결해줘봤자,
.touchUpInside 이벤트를 받고, 처리하는 객체는 Cell 보다 상위에 있는 뷰컨트롤러가 합니다.
그래서 self는 상위에 있는 뷰컨으로 바뀌어야 할 것이며, @objc함수로 뷰컨에다가 선언해야합니다.
그러면 셀 안에 굳이 VC를 전달하고, 다시 함수를 참조해야하는데,
그것보다는 Cell을 넣어주는 cellForRowAt단계에서 처리해주는 것이 더 깔끔하다고 생각합니다.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
cell.myButton.addTarget(self, action: #selector(myFunc(_:)), for: .touchUpInside)
return cell
}
요로깨
반응형