简体   繁体   中英

UINavigationBar BarButtomItem not dismissing the view controller swift

I have created UINavigationBar programatically and added barbuttonitem, the problem is when I click on that image, respective method is calling but view controller is not dismissing.

LocateVehicle

class LocateVehicle: UITableViewController{

let kCloseCellHeight: CGFloat = 130
let kOpenCellHeight: CGFloat = 488
let kRowsCount = 10
var cellHeights: [CGFloat] = []

let dataArr = ["Running", "Stopped", "Idle", "Running"]

@IBAction func backBarButton(_ sender: Any) {
}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.contentInset.top = UIApplication.shared.statusBarFrame.height

    setup()
}

private func setup() {
    cellHeights = Array(repeating: kCloseCellHeight, count: kRowsCount)
    tableView.estimatedRowHeight = kCloseCellHeight
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "background"))
}

 }
// MARK: - TableView
extension LocateVehicle {

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

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard case let cell as CustomLocateVehicleCell = cell else {
        return
    }

    cell.backgroundColor = .clear

    if cellHeights[indexPath.row] == kCloseCellHeight {
        cell.unfold(false, animated: false, completion: nil)
    } else {
        cell.unfold(true, animated: false, completion: nil)
    }

    cell.number = dataArr[indexPath.row]
//        cell.statusLabel.text = dataArr[indexPath.row]
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! CustomLocateVehicleCell

    let durations: [TimeInterval] = [0.26, 0.2, 0.2]
    cell.durationsForExpandedState = durations
    cell.durationsForCollapsedState = durations

//        cell.liveTrackButton.tag = indexPath.row;


   return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath.row]
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! FoldingCell

    if cell.isAnimating() {
        return
    }

    var duration = 0.0
    let cellIsCollapsed = cellHeights[indexPath.row] == kCloseCellHeight
    if cellIsCollapsed {
        cellHeights[indexPath.row] = kOpenCellHeight
        cell.unfold(true, animated: true, completion: nil)
        duration = 0.5
    } else {
        cellHeights[indexPath.row] = kCloseCellHeight
        cell.unfold(false, animated: true, completion: nil)
        duration = 0.8
    }

    UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in
        tableView.beginUpdates()
        tableView.endUpdates()

    }, completion: nil)

  }
}

LiveTrack

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    setNavigationBar()
  }

 func setNavigationBar() {
    let screenSize: CGRect = UIScreen.main.bounds
    let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: screenSize.width, height: 44))
    self.view.addSubview(navBar);
    let navItem = UINavigationItem(title: "AP 16 BD 5678");
    let image = UIImage(named: "ic_chevron_left_white")?.withRenderingMode(.alwaysOriginal)
    let doneItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backAction));
    navItem.leftBarButtonItem = doneItem;
    navBar.setItems([navItem], animated: false);
 }

 @IBAction func backAction(_ sender: Any) {
    print("back working")
   //self.navigationController?.popViewController(animated: true)
     dismiss(animated: true, completion: nil)
 }

I am navigation to view controller from tableview cell

let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let view = storyboard.instantiateViewController(withIdentifier: "LiveTrackStoryboard") as! LiveTrack
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    //show window
    appDelegate.window?.rootViewController = view

Please help me to solve this. Thanks in advance

Add button target in cellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! CustomLocateVehicleCell

    let durations: [TimeInterval] = [0.26, 0.2, 0.2]
    cell.durationsForExpandedState = durations
    cell.durationsForCollapsedState = durations
    cell.yourButton.addTarget(self, action:#selector(buttonClicked()), for: .touchUpInside)
    return cell
}

Perform Push on cell button action(You are making second controller root controller, so there is nothing to go back, so don't do that instead perform push, and add controller to stack) make sure your root controller is embedded to navigationController . -:

func buttonClicked(sender:UIButton){
      let storyboard = UIStoryboard(name: "Main", bundle: nil)
      let view = storyboard.instantiateViewController(withIdentifier: "LiveTrackStoryboard") as! LiveTrack
    // TO PUSH
        navigationController?.pushViewController(view,animated: true)
    // TO PRESENT
     present(view!, animated: true, completion: nil)
    }

Now in second controller where you have leftBarButton pop to previous controller -:

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setNavigationBar()
      }

     func setNavigationBar() {
        let screenSize: CGRect = UIScreen.main.bounds
        let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: screenSize.width, height: 44))
        self.view.addSubview(navBar);
        let navItem = UINavigationItem(title: "AP 16 BD 5678");
        let image = UIImage(named: "ic_chevron_left_white")?.withRenderingMode(.alwaysOriginal)
        let doneItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backAction));
        navItem.leftBarButtonItem = doneItem;
        navBar.setItems([navItem], animated: false);
     }

     @IBAction func backAction(_ sender: Any) {
        print("back working")
   // TO POP
      self.navigationController?.popViewController(animated: true)
   // TO DISMISS
   dismiss(animated: true, completion: nil)
     }

Perform any based on your need.

You also don't need to embed navigationController as root if you don't want to perform push.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM