developer tip

UITableViewCell이 선택되었을 때 push segue를 만드는 방법

copycodes 2020. 12. 2. 21:30
반응형

UITableViewCell이 선택되었을 때 push segue를 만드는 방법


테이블보기에 효과 목록이 있습니다. 새로운 효과를 만드는 데 도움이되는 다른 뷰 컨트롤러로 푸시 세그를 수행하는 오른쪽 상단 바 버튼을 만들었습니다. 이제 효과 값이 효과 추가보기 컨트롤러에로드되고 편집 된 값을 저장할 수 있도록 테이블보기 셀에 푸시 세그를 추가하려고합니다.

질문은 프로그래밍 방식으로 푸시 세그를 만들 수 있습니까? 그렇지 않으면 효과를 전달할 수 prepareforsegue있습니까? 를 사용하려고하면 prepareforsegue에서 컨트롤을 드래그 UITableView해도 효과 추가보기 컨트롤러에 대한 푸시 세그를 만들 수없는 문제가 발생 합니다.


control View Controller에서 View Controller로 드래그

View Controller에서 View Controlle로!

segue에 식별자를 제공해야합니다.

여기에 이미지 설명 입력

segue 수행 :

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"yourSegue" sender:self];
}

이제 여기에 해당 뷰 컨트롤러에 데이터를 전달해야하는 경우 segue가 수행됩니다. 그런 다음 다음 segue 대리자를 구현해야합니다.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"yourSegue"])
    {
        //if you need to pass data to the next controller do it here
    }
}

didSelectRowAtIndexPath를 사용할 필요가없는 또 다른 옵션이 있습니다.

Interface Builder의 segue를 프로토 타입 셀에서 대상으로 연결하기 만하면됩니다.

여기에서 간단하게 다음을 수행 할 수 있습니다.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "AffiliationDetail", let destination = segue.destinationViewController as? AffiliateDetailViewController {
        if let cell = sender as? UITableViewCell, let indexPath = tableView.indexPathForCell(cell) {
            var affiliation = affiliations[indexPath.row]
            destination.affiliation = affiliation
        }
    }
}

빠른

이 답변은 데이터를 전달하는 방법을 보여 주며 Xcode 8 및 Swift 3 용으로 업데이트되었습니다.

프로젝트를 설정하는 방법은 다음과 같습니다.

  • 기호가있는 프로젝트를 만듭니다 TableView. 간단한 예는 여기참조 하십시오 .
  • 두 번째 ViewController.
  • 테이블 뷰가있는 첫 번째 뷰 컨트롤러에서 두 번째 뷰 컨트롤러로 드래그를 제어합니다. segue 유형으로 "표시"를 선택합니다.

여기에 이미지 설명 입력

  • 스토리 보드에서 segue를 클릭 한 다음 Attribute Inspector에서 식별자 이름을 "yourSegue"로 지정합니다. (원하는대로 호출 할 수 있지만 코드에서 동일한 이름을 사용해야합니다.)

여기에 이미지 설명 입력

  • (선택 사항) 스토리 보드에서 첫 번째보기 컨트롤러를 선택하고 Editor> Embed In> Navigation Controller로 이동하여 모든 항목을 탐색 컨트롤러에 포함 할 수 있습니다 .

암호

TableView가있는 First View 컨트롤러 :

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    // ...


    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // Segue to the second view controller
        self.performSegue(withIdentifier: "yourSegue", sender: self)
    }

    // This function is called before the segue
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // get a reference to the second view controller
        let secondViewController = segue.destination as! SecondViewController

        // set a variable in the second view controller with the data to pass
        secondViewController.receivedData = "hello"
    }
}

두 번째보기 컨트롤러

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    // This variable will hold the data being passed from the First View Controller
    var receivedData = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        print(receivedData)
    }
}

View Controller 간의 데이터 전달에 대한 더 기본적인 예제는 이 답변을 참조하십시오 .


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"YourPushSegueName" sender:self];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyViewController *myVController = (MyViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"StoryBordIdentifier"];
    [self.navigationController pushViewController:myVController animated:YES];
}

두 가지 옵션이 있습니다. 프로토 타입 셀에서 새 vc로 ctrl + 드래그 한 다음 각 셀에서 segue를 실행하고 segue에 대한 준비를 구현해야합니다.

Second option, in didselectrowatindexpath you can instantiate your new viewcontroller using self.storyboard instantiateviewcontrollerwithidentifier..., then call pushviewcontroller or presentviewcontroller, you don't need segues in storyboard or prepare for segue in this scenario.


You can use this method :

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

You can perform a function on selection of a particular tableview cell in this.


You can do this by following methods:

Firstly you need to import another view controller in current view.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {}

inside above method you have to call a method - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated; like this:

yourViewController = [[YourViewController alloc] initWithNibName:@"YourViewController" bundle:nil];
[self.navigationController YourViewController animated:YES];

By this you can achieve push segue when UITableViewCell is selected..

Hope this may help you…!


Swift 3

After following up Ahmed Daou's answer -> manually drag segue from vc to vc at storyboard

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "SegueIdentifier", sender: nil)    
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "SegueIdentifier" {
        //do something you want
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    [self performSegueWithIdentifier:@"segueIdentifier" sender:indexPath];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"segueIdentifier"]) {
        NSIndexPath *indexPath = (NSIndexPath *)sender;

    }
}

참고 URL : https://stackoverflow.com/questions/22759167/how-to-make-a-push-segue-when-a-uitableviewcell-is-selected

반응형