简体   繁体   English

Swift Segue不会将数据传递到旧的ViewController

[英]Swift segue will not pass data to old ViewController

Apologies if this is dumb, I am new to coding. 抱歉,这很愚蠢,我是编码新手。 Cant find a previously asked Question that is relevant to this issue (the code appears to be correct). 无法找到与该问题相关的先前询问的问题(代码似乎正确)。

I am building a basic news feed app. 我正在构建一个基本的新闻提要应用程序。

On the main view controller FeedsTableViewController.swift I have a button that when pushed segues to AddFeedViewController.swift. 在主视图控制器FeedsTableViewController.swift上,我有一个按钮,当将按钮推到AddFeedViewController.swift时。

On AddFeedViewController I have a segue function that should take text from a UITextField (a web address for an RSS feed) and upon segue run a function (AddNewFeed) that enters the data into a TableView cell on FeedsTableViewController. 在AddFeedViewController上,我有一个segue函数,该函数应该从UITextField(RSS feed的网址)获取文本,并在segue运行时运行一个函数(AddNewFeed),该函数将数据输入FeedsTableViewController的TableView单元中。

Upon running the application I am able to segue back from FeedsTableViewController but no data is being passed into the cell in FeedsTableViewController. 运行该应用程序后,我可以从FeedsTableViewController进行筛选,但是没有数据传递到FeedsTableViewController的单元格中。 I know that AddNewFeed is working properly as I run the function automatically in viewDidLoad to hardcode in an RSS feed from Apple. 我知道AddNewFeed正常运行,因为我在viewDidLoad中自动运行该功能以硬编码来自Apple的RSS提要。

Only thing I can think of is that the data is not being pulled from UITextField properly or not entered correctly as a parameter into AddNewFeed. 我唯一能想到的是,数据没有从UITextField中正确提取,或者没有作为参数正确输入到AddNewFeed中。 No idea why this is isn't working, thoughts very much appreciated. 不知道为什么这是行不通的,非常感谢。

FeedsTableViewController code: FeedsTableViewController代码:

var feedUrl


    override func viewDidLoad() {
    super.viewDidLoad()

    AddNewFeed("http://developer.apple.com/news/rss/news.rss")

}


func AddNewFeed(url: String) {
    feedUrl = url
    let url : NSURL = NSURL(string: feedUrl)!


    parser = NSXMLParser(contentsOfURL: url)!
    parser.delegate = self
    parser.parse()
}

AddFeedViewController code: AddFeedViewController代码:

class AddFeedViewController: UIViewController {

@IBOutlet weak var feedUrl: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}




override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let feedsViewController = segue.destinationViewController as! FeedsTableViewController

    feedsViewController.AddNewFeed(feedUrl.text)

}

} }

Here is the code from the 2 class files: 这是来自2个类文件的代码:

FeedsTableViewController: FeedsTableViewController:

import UIKit 导入UIKit

class FeedsTableViewController: UITableViewController, NSXMLParserDelegate { FeedsTableViewController类:UITableViewController,NSXMLParserDelegate {

var parser : NSXMLParser = NSXMLParser()
var feedUrl : String = String()

var feedTitle : String = String()
var articleTitle : String = String()
var articleLink : String = String()
var articlePubDate : String = String()
var parsingChannel : Bool = false
var eName : String = String()

var feeds : [FeedModel] = []
var articles : [ArticleModel] = []


override func viewDidLoad() {
    super.viewDidLoad()

    AddNewFeed("http://developer.apple.com/news/rss/news.rss")

}


func AddNewFeed(url: String) {
    feedUrl = url
    let url : NSURL = NSURL(string: feedUrl)!


    parser = NSXMLParser(contentsOfURL: url)!
    parser.delegate = self
    parser.parse()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func retrieveNewsFeed(segue: UIStoryboardSegue){

}

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {

    eName = elementName
    if elementName == "channel" {
        feedTitle = String()
        feedUrl = String()
        parsingChannel = true

    } else if elementName == "item" {
        articleTitle = String()
        articleLink = String()
        articlePubDate = String()
        parsingChannel = false
    }

}

func parser(parser: NSXMLParser, foundCharacters string: String?) {
    let data = string!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

    if(!data.isEmpty){
        if parsingChannel {
            if eName == "title" {
                feedTitle += data
            }
        } else {
            if eName == "title" {
                articleTitle += data
            } else if eName == "link" {
                articleLink += data
            } else if eName == "pubDate" {
                articlePubDate += data
            }
        }
    }
}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "channel" {
        let feed : FeedModel = FeedModel()
        feed.title = feedTitle
        feed.url = feedUrl
        feed.articles = articles
        feeds.append(feed)


    } else if elementName == "item" {
        let article : ArticleModel = ArticleModel()
        article.title = articleTitle
        article.link = articleLink
        article.pubDate = articlePubDate
        articles.append(article)
    }
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return feeds.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("FeedCell", forIndexPath: indexPath) as! UITableViewCell

    let feed : FeedModel = feeds[indexPath.row]
    cell.textLabel!.text = feed.title

    return cell
}


/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
}
*/

/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}
*/

/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
}
*/


// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "ShowArticles" {
        let viewController: ArticlesTableViewController = segue.destinationViewController as! ArticlesTableViewController
        let indexPath = self.tableView.indexPathForSelectedRow()!
        let feed = feeds[indexPath.row]

        viewController.articles = feed.articles

    }
}
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.

/*
    if(segue.identifier == "SomeSegue"){
        var articlesController = segue.destinationViewController as! ArticlesTableViewController

        // gives access to the temp variable on the destination, now its ready to fire.

        articlesController.temp = "hello there"
    }
*/

}

AddFeedViewController: AddFeedViewController:

import UIKit 导入UIKit

class AddFeedViewController: UIViewController { class AddFeedViewController:UIViewController {

@IBOutlet weak var feedUrl: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let feedsViewController = segue.destinationViewController as! FeedsTableViewController

    feedsViewController.AddNewFeed(feedUrl.text)

}

} }

In your FeedsTableViewController add a new method (UIStoryboardSegue parameter is important here), for example: 在您的FeedsTableViewController添加一个新方法(UIStoryboardSegue参数在这里很重要),例如:

@IBAction func dismissToFeeds(segue:UIStoryboardSegue) {
    let addViewController = segue.sourceViewController as! AddFeedViewController

    // get data from addViewController
    let data = addViewController.feedUrl.text
    println("\(data)")
    // reload table view
}

In the storyboard in AddFeedViewController control tag from the button you use to dismiss the view to the unwind icon: 在故事板的AddFeedViewController控件标签中,您可以使用按钮将视图关闭到展开图标:

看到第三个“退出”图标

the third 'Exit' icon and select dismissToFeeds action. 第三个“退出”图标,然后选择dismissToFeeds操作。

whene the datasource is updated, you want to call reloadData to update the tableview. 数据源更新时,您要调用reloadData来更新表视图。 I think/guess that is the problem. 我认为/猜测是问题所在。

Conventionally, you want to create a field in your destination view controller instead of just parse it directly: the DestinationViewController may not be in the right lifecycle yet, just FYI 通常,您要在目标视图控制器中创建一个字段,而不是直接对其进行解析:DestinationViewController可能尚未处于正确的生命周期中,仅供参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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