我想創建一個tableView的用戶從我的Parse數據庫是在同一類(在學校)。所有用戶都必須擁有用戶名,但並不是所有用戶都會爲其提供全名或設置個人資料圖片。我用這個代碼:添加項目到特定表格查看行如果可用
let studentsQuery = PFQuery(className:"_User")
studentsQuery.whereKey("objectId", containedIn: studentsArray! as! [AnyObject])
let query2 = PFQuery.orQueryWithSubqueries([studentsQuery])
query2.findObjectsInBackgroundWithBlock {
(results: [PFObject]?, error: NSError?) -> Void in
if error != nil {
// Display error in tableview
} else if results! == [] {
spinningActivity.hideAnimated(true)
print("error")
} else if results! != [] {
if let objects = results {
for object in objects {
if object.objectForKey("full_name") != nil {
let studentName = object.objectForKey("full_name")! as! String
self.studentNameResults.append(studentName)
}
if object.objectForKey("username") != nil {
let studentUsername = object.objectForKey("username")! as! String
self.studentUsernameResults.append(studentUsername)
}
if object.objectForKey("profile_picture") != nil {
let studentProfilePictureFile = object.objectForKey("profile_picture") as! PFFile
studentProfilePictureFile.getDataInBackgroundWithBlock({ (image: NSData?, error: NSError?) in
if error == nil {
let studentProfilePicture : UIImage = UIImage(data: image!)!
self.studentProfilePictureResults.append(studentProfilePicture)
} else {
print("Can't get profile picture")
// Can't get profile picture
}
self.studentsTableView.reloadData()
})
spinningActivity.hideAnimated(true)
} else {
// no image
}
}
}
} else {
spinningActivity.hideAnimated(true)
print("error")
}
}
此代碼工作正常,如果所有的用戶都有一個用戶名,FULL_NAME,和profile_picture。但是,我不知道如何獲取用戶的用戶名的tableView
,並且只有當用戶有圖片時纔將用戶的姓名或圖片添加到用戶的相應tableViewCell
。這裏是我的tableView
是如何配置:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return studentUsernameResults.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("studentsCell", forIndexPath: indexPath) as! StudentsInClassInformationTableViewCell
cell.studentProfilePictureImageView.layer.cornerRadius = cell.studentProfilePictureImageView.frame.size.width/2
cell.studentProfilePictureImageView.clipsToBounds = true
cell.studentProfilePictureImageView.image = studentProfilePictureResults[indexPath.row]
cell.studentUsernameLabel.text = studentUsernameResults[indexPath.row]
cell.studentNameLabel.text = studentNameResults[indexPath.row]
return cell
}
的studentProfilePictureResults
,studentUsernameResults
,並提出從解析拉到用戶的圖片,用戶名和姓名的結果陣列studentNameResults
。如果用戶沒有個人資料圖片,我會收到錯誤Index is out of range
。顯然,這意味着有三個名字,三個用戶名和只有兩個圖片,Xcode不知道如何配置單元格。我的問題:如何設置一個用戶的用戶名的tableView,並將他們的名字和個人資料圖片放在同一個單元格中,只要他們有一個?
不要存儲單獨的數組。存儲一個PFObjects數組,我建議你使用[username(string):UIImage)字典作爲照片 – Paulw11
@ Paulw11當我查詢用戶的用戶名,名字和圖片時,我得到了所有的結果曾經,就像你正在談論的那樣(將結果存儲在一個數組中)。我會如何將用戶名,姓名和圖片存儲在一起?我還沒有玩過多少字典,但我認爲他們只能存儲兩(2)個結果。我如何儲存所有三(3)? –