我找不到任何相关信息。我想将我选择的行(带有复选标记的行)作为新创建的组发送到我的firebase数据库中。我在tableview之外创建了一个“创建组”按钮。我希望有更多关于如何从选定行传递数据的信息或资源,但我无法找到关于该主题的任何内容。我看到很多关于如何选中和取消选中带有复选标记的行的信息,但在我的情况下,没有任何关于将选定的带勾选的行的信息发送到数组或在线数据库的信息。
class FriendsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var userList = [Users]()
@IBOutlet weak var myTableView: UITableView!
@IBAction func createGroup(_ sender: Any) {
}
final let urlString = "https://api.lookfwd.io/v1/test/users"
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
myCell.selectionStyle = UITableViewCellSelectionStyle.none
myCell.nameLabel.text = userList[indexPath.row].name
return myCell
}
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithTask()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if myTableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark{
myTableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none}
else{
myTableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
}
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
if let response = data {
if let jsonData = try? JSONSerialization.jsonObject(with: response, options: .allowFragments) as? [String:Any] {
if let dataArray = (jsonData as AnyObject).value(forKey: "users") as? [[String:Any]] {
for data in dataArray{
let newUser = Users(data: data)
self.userList.append(newUser)
print(jsonData!)
}
}
OperationQueue.main.addOperation({
for use in self.userList {
print(use.name ?? "")
}
self.myTableView.reloadData()
})
print(jsonData!)
}
}
}).resume()
}
}
答案 0 :(得分:1)
您的用户对象存储在数组userList
中。您只需记录点击的索引,如
var selected = [String]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if myTableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark{
myTableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
let currentUser = userList[indexPath.row]
selected = selected.filter { $0 != currentUser.name}
}else{
myTableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
let currentUser = userList[indexPath.row]
selected.append(currentUser.name)
}
}
之后,当你想要获得所有选定的名字时
for username in self.selected{
print(username ?? "")
}