셀에서 UITableViewCell indexPath를 가져오는 방법은 무엇입니까?
어떻게 세포에서 그것을 얻을 수 있습니까?indexPath
순식간에UITableView
?
스택 오버플로와 구글을 검색해봤는데, 모든 정보가 반대로 나와 있습니다.액세스할 수 있는 방법이 있습니까?superView
/UITableView
그리고 나서 그 세포를 검색합니까?
컨텍스트에 대한 자세한 정보: 내가 가지고 있는 클래스는 두 개이며, 하나는 ""입니다.Cue
그리고 하나는 이라고 불립니다.CueTableCell
은 (의) 하위 입니다.UITableViewCell
)CueTableCell
는 의시적 표다니현입각의 입니다.Cue
(두 클래스 모두 서로에 대한 포인터가 있음).Cue
명령을 때 시각적 표현(" representation")이 됩니다.CueTableCell
의 다음 다의음)의Cue
를 선택해야 합니다.그래서 그Cue
는 class calls »를 합니다.select
음단의에 있는 Cue
목에서검다니를 합니다.UITableView
cell
그리고 그것을 부릅니다.selectRowAtIndexPath:animated:scrollPosition:
그것이 필요로 하는 것.indexPath
의 시대의UITableViewCell
.
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
이 기능은 일부에서 논란이 있는 것으로 간주되는 경우에도 UITableView 설명서를 읽는 데 도움이 됩니다(아래 주석 참조).
셀은 인덱스 경로가 무엇인지 알 필요가 없습니다.컨트롤러에는 데이터 모델을 기반으로 UI 요소를 조작하거나 UI 상호 작용을 기반으로 데이터를 수정하는 코드가 포함되어야 합니다.(MVC 참조)
UITableViewCell에서 사용해 보십시오.
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
편집: iOS 8.1.2 이상에서는 작동하지 않는 것 같습니다.그것을 지적해 준 크리스 프린스에게 감사합니다.
다음과 같이 셀의 .h 파일에 약한 tableView 속성을 넣습니다.
@property (weak,nonatomic)UITableView *tableView;
cellForRowAt에서 속성 할당인덱스 방법:
cell.tableView = tableView;
이제 셀의 indexPath가 필요한 곳이면 어디든지:
NSIndexPath *indexPath = [cell.tableView indexPathForCell:cell];
다음과 같은 간단한 팁을 사용해 볼 수 있습니다.
의 신의에UITableViewCell
클스래:
@property NSInteger myCellIndex; //or add directly your indexPath
당신의 그고당신에.cellForRowAtIndexPath
예:
...
[cell setMyCellIndex : indexPath.row]
이제, 당신은 어디서든 당신의 세포 색인을 검색할 수 있습니다.
"이것은 나쁜 생각이다"라고 말하는 사람들을 다루기 위해, 저의 경우, 이것에 대한 저의 필요는 제가 단추를 다는 것입니다.UITableViewCell
누르면 다른 보기에 대한 segue입니다.에 대한 이 아니기 에, 이은세자대선아택때이문에니기,[self.tableView indexPathForSelectedRow]
작동하지 않습니다.
두 가지 옵션이 있습니다.
- 뷰에 전달해야 하는 객체를 테이블 셀 자체에 저장합니다.이것이 효과가 있는 동안, 그것은 내가 가지고 있는 요점을 패배시킬 것입니다.
NSFetchedResultsController
특히 테이블이 긴 경우 모든 개체를 메모리에 저장하고 싶지 않기 때문입니다. - 인덱스 경로를 사용하여 가져오기 컨트롤러에서 항목을 검색합니다.네, 제가 가서 해결해야 한다는 것은 보기 흉해 보입니다.
NSIndexPath
하지만 궁극적으로 메모리에 물건을 저장하는 것보다 저렴합니다.
indexPathForCell:
올바른 사용 방법이지만 다음과 같은 방법이 있습니다(이 코드는 하위 클래스에서 구현되는 것으로 가정됨).UITableViewCell
:
// uses the indexPathForCell to return the indexPath for itself
- (NSIndexPath *)getIndexPath {
return [[self getTableView] indexPathForCell:self];
}
// retrieve the table view from self
- (UITableView *)getTableView {
// get the superview of this class, note the camel-case V to differentiate
// from the class' superview property.
UIView *superView = self.superview;
/*
check to see that *superView != nil* (if it is then we've walked up the
entire chain of views without finding a UITableView object) and whether
the superView is a UITableView.
*/
while (superView && ![superView isKindOfClass:[UITableView class]]) {
superView = superView.superview;
}
// if superView != nil, then it means we found the UITableView that contains
// the cell.
if (superView) {
// cast the object and return
return (UITableView *)superView;
}
// we did not find any UITableView
return nil;
}
추신. 제 실제 코드는 테이블 보기에서 이 모든 것에 액세스합니다. 하지만 저는 왜 누군가가 테이블 셀에서 이런 일을 직접 하기를 원하는지 예를 들어 설명하고 있습니다.
빨리
let indexPath :NSIndexPath? = (self.superview.superview as! UITableView)?.indexPathForCell(self)
이 질문에 대한 답은 사실 저에게 많은 도움이 되었습니다.
사용한NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
그sender
나의 경우는.UITableViewCell
그리고 그것으로부터 옵니다.prepareForSegue
방법.
나는 이것을 사용했습니다 왜냐하면 나는 그것이 없었기 때문입니다.TableViewController
그러나 나는 가지고 있었습니다.UITableView property outlet
나는 그 책의 제목을 알아내야 했습니다.Cell
따라서 indexPath를 알아야 합니다.
이것이 누구에게 도움이 되기를 바랍니다!
iOS 11.0에서는UITableView.indexPathForRow(at point: CGPoint) -> IndexPath?
:
if let indexPath = tableView.indexPathForRow(at: cell.center) {
tableView.selectRow
(at: indexPath, animated: true, scrollPosition: .middle)
}
셀의 중심점을 가져온 다음 tableView는 해당 점에 해당하는 indexPath를 반환합니다.
스위프트 3.0 이상-
사용자 지정 셀 내에서 인덱스 경로를 가져와야 하는 경우
if let tableView = self.superview as? UITableView{
if let indexPath = tableView.indexPath(for: self){
print("Indexpath acquired.")
}else{
print("Indexpath could not be acquired from tableview.")
}
}else{
print("Superview couldn't be cast as tableview")
}
실패 사례를 주의하는 것이 좋습니다.
tableView에 섹션이 하나만 있고 모든 셀의 높이가 동일한 경우에만 작동합니다.
//get current cell rectangle relative to its superview
CGRect r = [self convertRect:self.frame toView:self.superview];
//get cell index
int index = r.origin.y / r.size.height;
UITableViewCell에서 사용해 보십시오.
NSIndexPath *indexPath = [(UITableView *)self.superview.superview indexPathForCell:self];
스위프트 4.x
내 휴대폰에 대한 액세스를 제공하기 위해 다음과 같은 작업을 수행했습니다.
UIV View의 확장 기능이 있습니다.
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
그리고는..내 셀 클래스:
class SomeCell: UITableViewCell {
func someMethod() {
if let myViewController = self.parentViewController as? CarteleraTableViewController {
let indexPath : IndexPath = (myViewController.tableView).indexPath(for: self)!
print(indexPath)
}
}
}
그게 다 내가 생각하는 겁니다.
안부 전합니다.
언급URL : https://stackoverflow.com/questions/15711889/how-to-get-uitableviewcell-indexpath-from-the-cell
'programing' 카테고리의 다른 글
도커에 볼륨을 추가하지만 하위 폴더 제외 (0) | 2023.08.16 |
---|---|
.gitignore 특정 파일 제외 (0) | 2023.08.16 |
현재 날짜에 일을 추가하는 방법은 무엇입니까? (0) | 2023.08.16 |
탭 레이아웃 탭 선택 (0) | 2023.08.16 |
도커의 ASPNETCORE_ENERVICE (0) | 2023.08.16 |