【问题标题】:Segue not passing data to ViewControllerSegue 不向 ViewController 传递数据
【发布时间】:2015-09-02 04:38:04
【问题描述】:

我正在尝试从 TableView 传递数据,因此当按下单元格时,该单元格上的数据将被传输到 viewController 并在那里显示,但我似乎无法让它工作。我试过这些帖子:

swift segue not passing data from tableview

Passing data from tableView to ViewController in Swift

Pass data through unwind segue

但要么我收到导致应用程序崩溃的错误,要么它不显示任何内容。我想做的是让用户对另一个用户发布的帖子发表评论,所以我试图从帖子中获取信息以详细显示它,但这就是我遇到麻烦的地方。这是我用来从表格视图传递数据的函数:

func objectAtIndexPath(indexPath: NSIndexPath) -> PFObject {
    return self.timelineData[indexPath.row] as! PFObject
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if(segue.identifier == "lookPosts"){
        let VC = segue.destinationViewController as! DetailViewContoller
        let indexPath: NSIndexPath! = self.tableView.indexPathForSelectedRow()
        VC.post = self.objectAtIndexPath(indexPath!) as PFObject
    }
}

这是 DetailViewController 的类:

import UIKit
import Parse

class DetailViewContoller: UIViewController, UITableViewDelegate, UITextViewDelegate {

    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var postTextView: UITextView!
    @IBOutlet weak var commentTableView: UITableView!

    var post: PFObject?
    var commentView: UITextView?
    var footerView: UIView?
    var contentHeight: CGFloat = 0

    var comments: [String]?
    let FOOTERHEIGHT : CGFloat = 50;

    override func viewDidLoad() {
        super.viewDidLoad()

        commentTableView.delegate = self

        /* Setup the keyboard notifications */
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

        //gets the current user username
        usernameLabel.text = PFUser.currentUser()!.username as String?

        if(post?.objectForKey("comments") != nil) {
            comments = post?.objectForKey("comments") as? [String]
        }

        println(post)
        println(post?.objectForKey("content"))
        //self.postTextView.text = post?.objectForKey("content") as? String
    }

    override func viewWillAppear(animated: Bool) {
        super.viewDidAppear(animated)

        self.postTextView.text = post?.objectForKey("content") as? String
        println(postTextView.text)
    }


    func keyBoardWillShow(notification: NSNotification) {
        var info:NSDictionary = notification.userInfo!
        var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

        var keyboardHeight:CGFloat =  keyboardSize.height - 40


        var animationDuration:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat

        var contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0);
        self.commentTableView.contentInset = contentInsets
        self.commentTableView.scrollIndicatorInsets = contentInsets

    }

    func keyBoardWillHide(notification: NSNotification) {

        self.commentTableView.contentInset = UIEdgeInsetsZero
        self.commentTableView.scrollIndicatorInsets = UIEdgeInsetsZero
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let count = comments?.count {
            return count
        }
        return 0
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = commentTableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentTableViewCell
        cell.commentLabel?.text = comments![indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if self.footerView != nil {
            return self.footerView!.bounds.height
        }
        return FOOTERHEIGHT
    }

    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        footerView = UIView(frame: CGRect(x: 0, y: 0, width: commentTableView.bounds.width, height: FOOTERHEIGHT))
        footerView?.backgroundColor = UIColor(red: 243.0/255, green: 243.0/255, blue: 243.0/255, alpha: 1)
        commentView = UITextView(frame: CGRect(x: 10, y: 5, width: commentTableView.bounds.width - 80 , height: 40))
        commentView?.backgroundColor = UIColor.whiteColor()
        commentView?.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5)
        commentView?.layer.cornerRadius = 2
        commentView?.scrollsToTop = false

        footerView?.addSubview(commentView!)
        let button = UIButton(frame: CGRect(x: commentTableView.bounds.width - 65, y: 10, width: 60 , height: 30))
        button.setTitle("Reply", forState: UIControlState.Normal)
        button.backgroundColor = UIColor(red:  0/0.0, green: 179/255.0, blue: 204/255.0, alpha: 100.0/100.0)
        button.layer.cornerRadius = 5
        button.addTarget(self, action: "reply", forControlEvents: UIControlEvents.TouchUpInside)
        footerView?.addSubview(button)
        commentView?.delegate = self
        return footerView
    }


    //Hide keyboard after touching background
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

    //remaining characters
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{

        if (text == "\n") {
            textView.resignFirstResponder()
        }

        return true
    }

    func reply() {
        post?.addObject(commentView!.text, forKey: "comments")
        post?.saveInBackground()
        if let tmpText = commentView?.text {
            comments?.append(tmpText)
        }
        commentView?.text = ""
        println(comments?.count)
        self.commentView?.resignFirstResponder()
        self.commentTableView.reloadData()
    }
}

所以我的问题是:还有其他传递数据的方法吗?或者我做错了什么数据没有通过?

【问题讨论】:

  • 您是否检查过您的 segue 名称并确保 prepareForSegue 中的 if 子句中的代码块正在运行?
  • @vigneshv 我拥有它的方式让VC = segue.destinationViewController as! DetailViewContoller 使应用程序崩溃,我必须将其更改为:if let destinationVC = segue.destinationViewController as? DetailViewContoller {} 但一旦我将其更改为,它就不会显示数据
  • 它不应该让应用程序崩溃。这意味着强制转换失败,因此没有发送任何数据。确保你没有在这个 segue 中推送导航控制器,这应该很容易调试。
  • 就像 FruitAddict 说的,这可能是因为你的destinationViewController 不是DetailViewController,除了建议的 FruitAddict,确保你的 ViewController 在 storyboard 是 DetailViewController 的子类.
  • 这不是重点。确保lookPosts 指向DetailsViewController,而不是像包装导航控制器那样。还要确保该视图在情节提要中正确设置了其类。

标签: ios iphone swift cocoa-touch parse-platform


【解决方案1】:

这是实现这一目标的一种方法:

如果您的数据不大,那么您可以使用NSUserDefaults

首先将数据存储到内存中:

NSUserDefaults.standardUserDefaults().setObject(yourObject, forKey: "yourKey")

在另一个 viewController 中从内存中读取数据:

let yourObject = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as! PFObject

希望对你有帮助。

【讨论】:

  • 我不相信它很大,因为我只想传递用户单击的单元格的数据,所以我想这会起作用,但我应该在哪里应用呢?在prepareForSegue 函数内部?
  • 您可以将您的对象存储在didSelectRowAtIndexPath
  • 这将在应用程序范围内存储它仅供参考,您可以将数据存储在prepareForSegue 中。它也是持久的,所以即使用户退出应用程序,数据仍然会被存储。
  • @DharmeshKheni 以这种方式使用它我不需要执行 segue 功能对吗?
  • 我可以把它保存在cellForRowAtIndexPath吗?
猜你喜欢
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多