2017-01-07 67 views
0
let custom = Bundle.main.loadNibNamed("PostView", owner: self, options: nil)?.first as! PostView 
custom.layer.cornerRadius = customCard.bounds.width/64 
custom.textLabel.text = "number \(index)" 
custom.numberOfComment.text = "4" 
custom.ratingLabel.text = "+ 39" 
custom.ratingLabel.textColor = UIColor(red:0.61, green:0.92, blue:0.53, alpha:1.0) 

      return custom 

我想要做的是在單獨的文本中設置一個seval標籤。 xib文件,用下面顯示的代碼創建一個數組。Swift - 從數組中讀取

var posts:[Post] = [] 

func observeDatabase() { 

    let Ref = FIRDatabase.database().reference().child("posts") 
    Ref.observe(.childAdded, with: { snapshot in 

     let snapshotValue = snapshot.value as? NSDictionary 

     if let title = snapshotValue?["title"] as? String { 

      let postText = snapshotValue?["text"] as? String 
      let postName = snapshotValue?["name"] as? String 
      let postNumberOfComments = snapshotValue?["numberOfComments"] as? NSNumber 
      let postRating = snapshotValue?["rating"] as? NSNumber 
      let postID = snapshotValue?["postID"] as? String 

      self.posts.append(Post(name: postName as NSString?, image: UIImage(named: "none"), text: postText as NSString?, title: title as NSString?, comments: postNumberOfComments, rating: postRating, postID: postID)) 
     } 
    }) 
} 

並與結構

struct Post { 

      let Name: NSString 
      let Image: UIImage! // Should be optional in the future 
      let Title: NSString // Title 
      let Text: NSString // Text 
      let Comments: NSNumber? // Number of comments 
      let Rating: NSNumber // Number of up/down -votes 
      let PostID: String 

      var description: String { 
       return "Name: \(Name), \n Image: \(Image), Text: \(Text), Title: \(Title), Comments: \(Comments), Rating: \(Rating), PostID: \(PostID)" 
      } 

      init(name: NSString?, image: UIImage?, text:NSString?, title: NSString?, comments: NSNumber?, rating: NSNumber?, postID:String?) { 
       self.Name = name ?? "" 
       self.Image = image 
       self.Text = text ?? "" 
       self.Title = title ?? "" 
       self.Comments = comments ?? 0 
       self.Rating = rating ?? 0 
       self.PostID = postID ?? "" 
      } 
} 

問題:我如何讀取數組,並設置標籤的文本根據其indexpath? 謝謝!

回答

2

假設你已經在你的.xib文件的tableView因您參考indexPath:

可以使用提取後針對特定行:

let post = posts[indexPath.row] 

假設你有一個名爲UILabelnameLabel你可以設置它的文本屬性使用:

nameLabel.text = post.Name 
+0

非常感謝你! – Victor