2014-10-13 4 views
1

Я не могу найти, где я не разворачивал свой ярлык, чтобы я мог выполнять мой сеанс. Он продолжает говорить, что этикетка не имеет .text фатальной ошибки: неожиданно нашел ноль в то время как разворачивание необязательного значенияSegue from tableview для просмотра контроллера

Я просто пытаюсь сделать заголовок моего точки зрения контроллера, равного тексту метки teamNameLabel

import UIKit 

class TimelineTableViewController: UITableViewController { 

    var timelineData:NSMutableArray! = NSMutableArray() 

    override init(style: UITableViewStyle) { 
     super.init(style: style) 
     // Custom initialization 
    } 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 


    @IBAction func loadData(){ 
     timelineData.removeAllObjects() 

     var findTimelineData:PFQuery = PFQuery(className: "Sweets") 

     findTimelineData.findObjectsInBackgroundWithBlock{ 
      (objects:[AnyObject]!, error:NSError!)->Void in 

      if error == nil{ 
       for object in objects{ 
        let sweet:PFObject = object as PFObject 
        self.timelineData.addObject(sweet) 
       } 

       let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects 
       self.timelineData = NSMutableArray(array: array) 

       self.tableView.reloadData() 

      } 

     } 
    } 

    override func viewDidAppear(animated: Bool) { 
     self.loadData() 

     if PFUser.currentUser() == nil{ 
      var loginAlert:UIAlertController = UIAlertController(title: "Sign Up/Login", message: "Please sign up or login", preferredStyle: UIAlertControllerStyle.Alert) 

      loginAlert.addTextFieldWithConfigurationHandler({ 
        textfield in 
        textfield.placeholder = "Your username" 
       }) 

      loginAlert.addTextFieldWithConfigurationHandler({ 
       textfield in 
       textfield.placeholder = "Your password" 
       textfield.secureTextEntry = true 
      }) 

      loginAlert.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.Default, handler: { 
        alertAction in 
       let textFields:NSArray = loginAlert.textFields! as NSArray 
       let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField 
       let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField 

       PFUser.logInWithUsernameInBackground(usernameTextfield.text, password: passwordTextfield.text){ 
        (user:PFUser!, error:NSError!)->Void in 
        if user != nil{ 
         println("Login successfull") 
        }else{ 
         println("Login failed") 
        } 


       } 




       })) 

      loginAlert.addAction(UIAlertAction(title: "Sign Up", style: UIAlertActionStyle.Default, handler: { 
       alertAction in 
       let textFields:NSArray = loginAlert.textFields! as NSArray 
       let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField 
       let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField 

       var sweeter:PFUser = PFUser() 
       sweeter.username = usernameTextfield.text 
       sweeter.password = passwordTextfield.text 

       sweeter.signUpInBackgroundWithBlock{ 
        (success:Bool!, error:NSError!)->Void in 
        if error == nil{ 
         println("Sign Up successfull") 
        }else{ 
         let errorString = error.localizedDescription 
         println(errorString) 
        } 


       } 



       })) 

      self.presentViewController(loginAlert, animated: true, completion: nil) 
     } 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Uncomment the following line to preserve selection between presentations 
     // self.clearsSelectionOnViewWillAppear = false 

     // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
     // self.navigationItem.rightBarButtonItem = self.editButtonItem 
    } 

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

    // #pragma 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 timelineData.count 
    } 


    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell { 
     let cell:SweetTableViewCell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath!) as SweetTableViewCell 

     let sweet:PFObject = self.timelineData.objectAtIndex(indexPath!.row) as PFObject 

    cell.sweetTextView.alpha = 0 
    cell.timestampLabel.alpha = 0 
    cell.usernameLabel.alpha = 0 
    cell.teamNameLabel.alpha = 0 

     cell.sweetTextView.text = sweet.objectForKey("content") as String 

     cell.teamNameLabel.text! = sweet.objectForKey("teamName") as String 


     var dataFormatter:NSDateFormatter = NSDateFormatter() 
     dataFormatter.dateFormat = "yyyy-MM-dd HH:mm" 
     cell.timestampLabel.text = dataFormatter.stringFromDate(sweet.createdAt) 

     var findSweeter:PFQuery = PFUser.query() 
     findSweeter.whereKey("objectId", equalTo: sweet.objectForKey("sweeter").objectId) 

     findSweeter.findObjectsInBackgroundWithBlock{ 
      (objects:[AnyObject]!, error:NSError!)->Void in 
      if error == nil{ 
       let user:PFUser = (objects as NSArray).lastObject as PFUser 
       cell.usernameLabel.text = user.username 


       UIView.animateWithDuration(0.5, animations: { 
         cell.sweetTextView.alpha = 1 
         cell.timestampLabel.alpha = 1 
         cell.usernameLabel.alpha = 1 
         cell.teamNameLabel.alpha = 1 
        }) 
      } 
     } 


     return cell 
    } 



    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     // Get the new view controller using [segue destinationViewController]. 
     // Pass the selected object to the new view controller. 
     if segue.identifier == "viewTeam" { 

      if let indexPath = self.tableView.indexPathForSelectedRow() { 
       let vc = segue.destinationViewController as TeamViewController 
       vc.title = timelineData[indexPath.row].teamNameLabel.text 
      } 

      /* 
      if let indexPath = self.tableView.indexPathForSelectedRow() { 
      let controller = (segue.destinationViewController as UINavigationController).topViewController as TeamViewController 
      controller.title = timelineData[indexPath.row].teamNameLabel 
      */ 

      //viewController.title = TimelineData.teamNameLabel.text 
      //} 
     } 

    } 

Моя проблема заключается в моей подготовке сообщение SEGUE

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     // Get the new view controller using [segue destinationViewController]. 
     // Pass the selected object to the new view controller. 
     if segue.identifier == "viewTeam" { 

      if let indexPath = self.tableView.indexPathForSelectedRow() { 
       let vc = segue.destinationViewController as TeamViewController 
       vc.title = timelineData[indexPath.row].teamNameLabel.text 
      } 

      /* 
      if let indexPath = self.tableView.indexPathForSelectedRow() { 
      let controller = (segue.destinationViewController as UINavigationController).topViewController as TeamViewController 
      controller.title = timelineData[indexPath.row].teamNameLabel 
      */ 

      //viewController.title = TimelineData.teamNameLabel.text 
      //} 
     } 

    } 

Вот мой класс клеток

import UIKit 

class SweetTableViewCell: UITableViewCell { 

    @IBOutlet var usernameLabel: UILabel! = UILabel() 
    @IBOutlet var timestampLabel: UILabel! = UILabel() 
    @IBOutlet var teamNameLabel: UILabel! = UILabel() 
    @IBOutlet var sweetTextView: UITextView! = UITextView() 
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
     super.init(style: style, reuseIdentifier: reuseIdentifier) 
     // Initialization code 
    } 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 
     //teamNameLabel.text = "" 
    } 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override func setSelected(selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 

     // Configure the view for the selected state 

    } 

} 

Это сводит меня с ума

ответ

0

Я считаю, что проблема заключается в том, что в вашем методе prepareForSegue вы устанавливаете заголовок на неправильном экземпляре вашего контроллера вида.

Вы создаете переменную vc и устанавливаете заголовок на ней, но это не меняет экземпляр destinationViewController.

Попробуйте этот код:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
    if segue.identifier == "viewTeam" { 

     if let indexPath = self.tableView.indexPathForSelectedRow() { 
      (segue.destinationViewController as TeamViewController).title = timelineData[indexPath.row].teamNameLabel.text 
     } 

     /* 
     if let indexPath = self.tableView.indexPathForSelectedRow() { 
     let controller = (segue.destinationViewController as UINavigationController).topViewController as TeamViewController 
     controller.title = timelineData[indexPath.row].teamNameLabel 
     */ 

     //viewController.title = TimelineData.teamNameLabel.text 
     //} 
    } 

} 
+0

Это еще не сработало .. оно все еще говорит UILabel! не имеет члена с именем text – xduvall15x

+0

ok, так что теперь я получил его, чтобы распознать текст в метке с помощью (segue.destinationViewController как TeamViewController) .title = timelineData [indexPath.row] .teamNameLabel! .text, но теперь его высказывание дает мне ошибка Thread 1: EXC_BAD_INSTRUCTION (код .. blah blah – xduvall15x

+0

В вашем окне вывода должно быть больше информации о том, что именно пытается ваша программа, но не в состоянии сделать. – mtaylor

0

хорошо я получил его !!! Heres my segue

// In a storyboard-based application, you will often want to do a little preparation before navigation 
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
    if segue.identifier == "viewTeam" { 


     if let indexPath = self.tableView.indexPathForSelectedRow() { 
      println(timelineData[indexPath.row] .valueForKey("teamName")) //.teamNameLabel?.text) 

     (segue.destinationViewController as TeamViewController).title = timelineData[indexPath.row] .valueForKey("teamName")! as? String 
     } 

     /* 

     if let indexPath = self.tableView.indexPathForSelectedRow() { 
     let controller = (segue.destinationViewController as TeamViewController).topViewController as TeamViewController 
     controller.title = timelineData[indexPath.row].teamNameLabel!.text 
     */ 

     //viewController.title = TimelineData.teamNameLabel.text 
     //} 
    } 

} 
Смежные вопросы