Programing

신속하게 터치하거나 클릭 한 tableView 셀을 감지하는 방법

crosscheck 2020. 11. 1. 17:21
반응형

신속하게 터치하거나 클릭 한 tableView 셀을 감지하는 방법


나는 index선택한 항목 을 가져 와서 TableView그 후에 활동을 시작 하려고 합니다. 불행히도 내가 찾은 대부분의 솔루션은 Objective-c에 있거나 작동하지 않습니다.

라벨을 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)인쇄하지 않는 방법 cell..

누군가 제발 도와 줄 수 있습니까?

UIKit 가져 오기
ResearchKit 가져 오기

class TaskListViewController : UIViewController, UITableViewDataSource {

    let tasks = [( "짧은 걷기"),
        ( "청력 측정"),
        ( "손가락 두드리기"),
        ("반응 시간"),
        ( "공간 스팬 메모리")
    ]


    // 테이블에있는 섹션 수
    func numberOfSectionsInTableView (tableView : UITableView)-> Int {
        반환 1
    }

    // int 몇 행을 반환
    func tableView (tableView : UITableView, numberOfRowsInSection 섹션 : Int)-> Int {
        task.count 반환
    }

    // 내용은 무엇입니까

    func tableView (tableView : UITableView, cellForRowAtIndexPath indexPath : NSIndexPath)-> UITableViewCell {
        var cell = UITableViewCell ()

        var (testName) = tasks [indexPath.row]
        cell.textLabel? .text = testName
        리턴 셀
    }

    // 각 테이블 섹션에 이름 지정

    func tableView (tableView : UITableView, titleForHeaderInSection 섹션 : Int)-> 문자열? {

        반환 "작업"

    }

    func tableView (tableView : UITableView, didSelectRowAtIndexPath indexPath : NSIndexPath) {

        let indexPath = tableView.indexPathForSelectedRow ();

        currentCell = tableView.cellForRowAtIndexPath (indexPath!) as UITableViewCell!

        println (currentCell.textLabel! .text)
    }


    override func viewDidLoad () {
        super.viewDidLoad ()

    }  
}

몇 번의 시도 끝에 내가 찾은 튜토리얼과 다른 코드로 코드를 변경했습니다. 그리고 그것은 너무 작동하지 않습니다. 이제 이것이 iOS 시뮬레이터의 문제라고 생각합니다 ...

UIKit 가져 오기
ResearchKit 가져 오기

class TaskListViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet
    var tableView : UITableView?
    var items : [String] = [ "We", "Heart", "Swift"]

    override func viewDidLoad () {
        super.viewDidLoad ()

        self.tableView! .registerClass (UITableViewCell.self, forCellReuseIdentifier : "cell")
    }


    func tableView (tableView : UITableView, numberOfRowsInSection 섹션 : Int)-> Int {
        return self.items.count;
    }

    func tableView (tableView : UITableView, cellForRowAtIndexPath indexPath : NSIndexPath)-> UITableViewCell {
        var cell : UITableViewCell = self.tableView! .dequeueReusableCellWithIdentifier ( "cell") as! UITableViewCell

        cell.textLabel? .text = self.items [indexPath.row]

        리턴 셀
    }

    func tableView (tableView : UITableView, didSelectRowAtIndexPath indexPath : NSIndexPath) {
        println ( "# \ (items [indexPath.row]) 셀을 선택했습니다!")
    }

}


셀의 값을 원하면 셀을 다시 만들 필요가 없습니다. didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(tasks[indexPath.row])
}

작업은 다음과 같습니다.

let tasks=["Short walk",
    "Audiometry",
    "Finger tapping",
    "Reaction time",
    "Spatial span memory"
]

또한 cellForRowAtIndexPath식별자를 설정해야하는지 확인해야합니다.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    var (testName) = tasks[indexPath.row]
    cell.textLabel?.text=testName
    return cell
}

도움이 되었기를 바랍니다.


Swift 3.0에서

델리게이트 메소드를 통해 tableview의 셀 터치 / 클릭 이벤트를 찾을 수 있습니다. 또한 이와 같이 셀의 섹션 및 행 값을 찾을 수 있습니다.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       print("section: \(indexPath.section)")
       print("row: \(indexPath.row)")
}

일어나야 할 몇 가지 일 중 ...

  1. 뷰 컨트롤러는 유형을 확장해야합니다. UITableViewDelegate

  2. 뷰 컨트롤러는 didSelectRowAt함수 를 포함해야 합니다.

  3. 테이블 뷰에는 뷰 컨트롤러가 델리게이트로 할당되어 있어야합니다.


아래는 델리게이트를 할당 할 수있는 곳입니다 (뷰 컨트롤러 내에서).

override func loadView() {
    tableView.dataSource = self
    tableView.delegate = self
    view = tableView
}

그리고 기능의 간단한 구현 didSelectRowAt.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("row: \(indexPath.row)")
}

weheartswift 튜토리얼을 사용하여 직접 문제를 해결했습니다.

enter image description here


이것은 나를 위해 잘 작동했습니다.

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("section: \(indexPath.section)")
        print("row: \(indexPath.row)")
    }

출력은 다음과 같아야합니다.

section: 0
row: 0

tableview 위임 및 데이터 소스를 상속하십시오. 필요한 것을 위임하십시오.

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

마지막으로이 대리자를 구현합니다.

     func tableView(_ tableView: UITableView, didSelectRowAt  
     indexPath: IndexPath) {
     print("row selected : \(indexPath.row)")
  }

신속하게 터치하거나 클릭 한 tableView 셀의 배열에서 요소를 가져 오려면

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel?.text= arr_AsianCountries[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexpath = arr_AsianCountries[indexPath.row]
print("indexpath:\(indexpath)")
}

 # Check delegate? first must be connected owner of view controller

    # Simple implementation of the didSelectRowAt function.

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         print("row selection: \(indexPath.row)")
    }

I screw up on the every time! Just make sure the tableView delegate and dataSource are declared in viewDidLoad. Then I normally populate a few arrays to simulate returned data and then take it from there!

//******** Populate Table with data ***********
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SetupCellView
    cell?.ControllerLbl.text = ViewContHeading[indexPath.row]
    cell?.DetailLbl.text = ViewContDetail[indexPath.row]
    cell?.StartupImageImg.image = UIImage(named: ViewContImages[indexPath.row])
    return cell!
}

참고URL : https://stackoverflow.com/questions/31182847/how-to-detect-tableview-cell-touched-or-clicked-in-swift

반응형