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
我要做的是在一个单独的。xib
文件中设置一个seval标签的文本,并使用下面显示的代码创建一个数组。
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
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 ?? ""
}
}
问题:如何读取数组并根据其索引路径设置标签文本? 谢谢!
答案 0 :(得分:2)
假设您在.xib文件中有一个tableView,因为您引用了indexPath:
您可以使用以下方式提取特定行的帖子:
let post = posts[indexPath.row]
假设您有一个名为UILabel
的{{1}},您可以使用以下方式设置其文字属性:
nameLabel