I've had this problem before and fixed it by embedding a button in each cell. Inside your UITableView
you should try embedding each cell with a UIButton
.
First make a custom UITableViewCell
in a separate file. Then drag and make an IBOutlet
for your UIButton
inside your custom cell.
class MyCustomCell: UITableViewCell{
@IBOutlet weak var followButton: UIButton!
var isFollowing:Bool = false
//Declare other cell attributes here like picture, name, gender
// ......
}
When you query and gather the data for your cells, you can store them in an array in your UITableViewController
. For example, var myCellArray = [MyCustomCell]()
. Then your UITableViewController
will look something like this:
var myCellArray = [userListTableViewCell]()
override func viewDidLoad(){
super.viewDidLoad()
var userQuery = PFUser.query()
userQuery.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
if let usersArray = objects as! [PFUser] {
self.myCellArray.removeAll(keepCapacity: false)
for user in usersArray {
if let user = object as? PFUser {
if user.objectId != PFUser.currentUser()?.objectId {
var myCell = userListTableViewCell()
myCell.userID = user.objectId
myCell.username = user["fullName"] as! String
myCell.gender = user["gender"] as! String
var userPicture = user["profilePicure"] as? PFFile
var image = UIImage(data:userPicture!.getData()!)
myCell.displayPicture.image = image
myCellArray.append(myCell)
self.tableView.reloadData()
}
}
}
}
})
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
myCellArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier") as! userListTableViewCell
//Edit the storyboard labels for each cell:
cell.username.text = myCellArray[indexPath.row].username
// etc....
//Embed a button with each cell
cell.followButton.layer.setValue(indexPath.row, forKey: "index")
cell.followButton.addTarget(self, action: "followButtonTapped:", for ControlEvents: UIControlEvents.TouchUpInside)
if (myCellArray[indexPath.row].isFollowing == false){
cell.followButton.setTitle("Follow", forState: .Normal)
}else{
cell.followButton.setTitle("Unfollow", forState: .Normal)
}
return cell
}
func followButtonTapped(sender: UIButton){
let cellIndex : Int = (sender.layer.valueForKey("index")) as! Int
//You now have the index of the cell whose play button was pressed so you can do something like
if (myCellArray[cellIndex].isFollowing == false){
myCellArray[cellIndex] = true
}else{
myCellArray[cellIndex] = false
}
self.tableView.reloadData()
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…