我有一个使用此代码的父视图控制器:
@IBOutlet weak var artist1: UILabel!
@IBAction func unwindFromArtist(segue: UIStoryboardSegue) {
//add artist
let source = segue.source as? ViewControllerArtistSearch
//Getting new artist and setting it to the appropriate artist label
artist1.text = (source?.favoriteArtist)!
}
我正在用此代码模态呈现一个表视图控制器:
import UIKit
import Alamofire
class ViewControllerArtistSearch: UITableViewController, UISearchBarDelegate {
var names = [String]()
var favoriteArtist: String = "fuckdickdonteattidepods"
@IBOutlet weak var artistSearch: UISearchBar!
//What happens with search is clicked
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let keywords = searchBar.text
let searchkeywords = keywords?.replacingOccurrences(of: " ", with: "+")
searchURL = "https://itunes.apple.com/search?term=\(String(describing: searchkeywords!))&entity=musicArtist"
callAlamo(url: searchURL)
}
var searchURL: String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
func callAlamo(url: String){
Alamofire.request(url).responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}
//Going through the json response from itunes and parsing out only the artist name
func parseData(JSONData: Data) {
do {
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as? [String : AnyObject]
if let results = readableJSON!["results"] as? NSArray{
for i in 0..<results.count{
let artist = results[i] as? NSDictionary
let artistName = artist?["artistName"]
names.append((artistName as? String ?? "artist"))
self.tableView.reloadData()
}
}
}
catch {
print(error)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell?.textLabel?.text = names[indexPath.row]
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
favoriteArtist = (names[indexPath.row])
print(favoriteArtist)
}
我进行了设置,以便当用户从表视图中选择一个单元格时,将执行展开选择以移回到父级vc。
但是我也对其进行了设置,以便代码使用didSelectRowAt从行中获取值并将其设置为空字符串以传递回父级。
问题在于,在将值从行中拉出并设置为变量之前执行了segue,因此传递回父级的值是默认的“ fuckdickdonteattidepods”。
我完全陷在这个问题上,任何建议将不胜感激!
最佳答案
好吧,我想到的第一件事是删除展开窗口,使用unwindSegueIdentifier
创建手动展开窗口(see this answer),然后在didSelectRowAt
中以编程方式调用它:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
favoriteArtist = (names[indexPath.row])
print(favoriteArtist)
self.performSegue(withIdentifier: "unwindSegueIdentifier", sender: self)
}
关于ios - 在Modal View Controller中过早消除Segue发生,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48421402/