2016년 9월 7일 수요일

UITableView delegate 사용 @@ in Swift2.x - Xcode 7.3 iOS 9.3




UIViewController에 UITableView의 델리게이트패턴을 사용하는 방법


UITableViewDataSource, UITableViewDelegate 추가해준다.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate


스토리보드에서 UITableView를 끌어 아울렛을 만들거나 아니면

@IBOutlet var tableView: UITableView!


뷰를 코드로 만들어줘도 상관 없다

let tableView: UITableView = UITableView(frame: CGRect(x: 10, y: 50, width: 200, height:600), style: UITableViewStyle.Plain)


테이블에 나타낼 데이터를 만들고

let Datalist = ["1", "2", "3", "4"]


viewDidLoad() 에 tableView.delegate = self, tableView.dataSource = self 코딩하면

override func viewDidLoad() {
  super.viewDidLoad()
  tableView.delegate = self
  tableView.dataSource = self
}



UITableViewDelegate 메소드를 사용할 수 있게 된다

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return Datalist.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath:indexPath)
  let row = indexPath.row
  cell.textLabel?.text = Datalist[row]
  return cell

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  tableView.deselectRowAtIndexPath(indexPath, animated: true)
  let row = indexPath.row
  print(Datalist[row])
}


댓글 없음:

댓글 쓰기

추천 게시물

애플 개발자 등록방법 2016년 5월 8일 기준!!

애플 개발자 등록 절차 1. 개발자 등록 페이지 이동    애플 개발자 로그인 > Account 페이지 이동 > 하단 영역 클릭 (이미지 참조)   >> Enroll 클릭 >> 무조건 승인!! ...