Мое положение состоит из UITable, который при выборе строки открывает новый VC и отправляет через пару переменных.Выполнение Segue перед функцией DidSelectAtRow
Моя проблема заключается в том, что segue выполняется до выполнения функции DidSelectAtRow.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print ("hello")
self.selectedCellTitle = self.communities[indexPath.row]
self.cellId = indexPath.row
print ("now here: ", communityIds[cellId!])
self.performSegue(withIdentifier: "showCommunitySegue", sender: self)
}
Я знаю это, потому что print
команды выше не выполняется. Приложение затем вылетает, когда следующий экран, потому что переменные, которые, как ожидается, будут там (cellId)
, являются нулевыми.
Если я удалю segue в раскадровке и запустим, все выходные отладки в этой функции будут работать правильно. Как только я снова создаю сеанс, приложение переключается на новый экран и вылетает, прежде чем запускается какой-либо из этих надстроек.
Чтобы создать свой SEGUE Я:
1) правой кнопкой мыши на ячейке в моем UITableView на VC1 в раскадровке и перетащив к моему VC2
2) выбор типа, как show
3) копируя имя идентификатора segue из функции prepare for segue
в VC 1 и вставляя его в атрибут identifier
в раскадровке для нового сеанса.
Любые идеи?
Ниже приведен полный код для VC1:
import UIKit
class CommunitiesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var selectedCellTitle: String?
var cellId: Int?
var communities = [String]() //{ didSet { communitiesTableView.reloadData()
// }
// }
var communityIds = [String]()
var flag = true
var userEmailText: String?
var tempComId: Int?
@IBOutlet weak var joinCommunityButton: UIButton!
@IBOutlet weak var createCommunityButton: UIButton!
@IBOutlet weak var communitiesTableView: UITableView!
override func viewDidLoad() {
self.communitiesTableView.delegate = self
self.communitiesTableView.dataSource = self
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.communities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
cell.textLabel?.text = self.communities[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print ("hello")
self.selectedCellTitle = self.communities[indexPath.row]
self.cellId = indexPath.row
print ("now here: ", communityIds[cellId!])
self.performSegue(withIdentifier: "showCommunitySegue", sender: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
if flag == true
{
self.communitiesTableView.reloadData()
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getDetails.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email=\(self.userEmailText!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
if let arr = json?["communities"] as? [[String:String]] {
self.communities = arr.flatMap { $0["name"]!}
self.communitiesTableView.reloadData()
}
} catch{
print(error)
}
}
}
task.resume()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "createCommunitySegue" {
let createCommunityController: CreateNewCommunity = segue.destination as! CreateNewCommunity
createCommunityController.myEmail = self.userEmailText
}
if segue.identifier == "joinCommunitySegue" {
let joinCommunityController: JoinCommunity = segue.destination as! JoinCommunity
joinCommunityController.myEmail = self.userEmailText
}
if segue.identifier == "showCommunitySegue" {
let showCommunityController: ShowCommunityViewController = segue.destination as!ShowCommunityViewController
print("yes here: ", self.cellId!)
showCommunityController.communityIsCalled = self.selectedCellTitle
showCommunityController.comIds = self.communityIds
showCommunityController.communityId = self.cellId
}
}
}
вам должен создать segue из верхнего контура viewcontroller, а не из ячейки – Vinodh
Создать segue из ViewController в ViewController – Rajat
, пожалуйста, используйте следующую запись, чтобы узнать, как переделывать и использовать ее программно http: //stackoverflow.com/a/21205550/1142743 – Vinodh