2016-07-12 2 views
-1

저는 UITableViews로 작업하기 시작했으며 코드가있는 셀의 위치를 ​​변경하는 방법을 찾을 수 없습니다. 스토리 보드에서 위치를 변경하는 것은 간단하지만 충분히 신속하게 수행 할 수 있어야합니다.셀의 인덱스 변경

+0

테이블 뷰 내에서 셀의 인덱스/순서를 변경한다고 가정합니다. tableview의 데이터 소스에서 셀의 데이터 순서를 변경하고'tableview.reloadData() '를 호출해야합니다. –

답변

0

TLDR;

  1. 데이터를 업데이트하십시오. 즉 swap(&arr[2], &arr[3])입니다.
  2. 데이터 변경 내용을 반영하기 위해 tableView의 reloadData() 메서드를 호출하십시오.

긴 대답

가 필요로하는 정보를 데이터 소스 (UITableViewDataSource)를 확인하여 UITableView 작품의 인스턴스입니다. 테이블 뷰가 사용할 UITableViewCell의 인스턴스뿐만 아니라 섹션 및 행의 수를 포함합니다. 이들은 다음 UITableViewDataSource 위임 방법으로 정의됩니다

override func numberOfSectionsInTableView(tableView: UITableView) -> Int; 
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int; 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell; 

일반적으로, 당신은 당신이 가진 일부 데이터, 가능성이 배열 또는 이와 유사한 용기에 전 두 기초 것입니다. - 예를 들어, 경우있는 tableView가 (다른 과일의 이름이 포함 된 문자열 목록을) fruitArray라는 이름의 배열에서 데이터를 표시 한 후 다음과 같이 할 수도 있습니다 : 다음

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // Our array is one dimensional, so only need one section. 
    // If you have an array of arrays for example, you could set this using the number of elements of your child arrays 
    return 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // Number of fruits in our array 
    return fruitArray.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("yourCellId") // Set this in Interface Builder 
    cell.textLabel?.text = fruitArray[indexPath.row] 
    return cell 
} 

을, 당신이 볼 수있는 귀하의 질문에 대한 답변이 간단 해집니다! 주어진 셀의 내용은 fruitArray을 기반으로하므로 배열을 업데이트하기 만하면됩니다. 그러나 당신은 어떻게 tableView에 dataSource를 "다시 검사"하게합니까? 글쎄, 당신은 지금처럼 reloadData 방법을 사용하십시오

swap(&fruitArray[2], &fruitArray[3]) 
tableView.reloadData() 

이 다음 따라서 화면에 표시하는 데이터 교환의 원인이 자사의 데이터 소스를 "다시 확인"할 수있는 tableView를 트리거!

는 세포의 위치를 ​​교환 할 수 있도록 사용자를하고 싶은 경우, 다음과 같은 UITableViewDelegate를 사용할 수 있습니다 (안 UITableViewDataSource) 위임 방법 :

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool 

this article에서보기를위한 되세요 더 많은 정보. 자세한 내용은 UITableView, UITableViewDataSourceUITableViewDelegate에 대한 Apple 설명서를 참조하십시오.

희망이 도움이됩니다.

+0

Jason에게 정말 감사드립니다. –

+0

귀하의 질문에 답변이되었다고 생각되면 답변을 수락으로 표시하십시오. 감사! – Jason