选择多个集合视图单元格并存储在数组中

时间:2015-11-11 09:35:10

标签: ios swift mobile

我正在为Swift中的iOS App开发一个入门流程。我想允许用户在集合视图中点击其他用户并让他们关注这些用户。我需要集合视图才能允许选择多个单元格,将单元格存储在一个数组中,并在用户点击下一个按钮后运行一个函数。这是我的控制器代码:

class FollowUsers: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

var tableData: [SwiftyJSON.JSON] = []

@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var loadingView: UIView!

private var selectedUsers: [SwiftyJSON.JSON] = []

override func viewDidLoad() {
    super.viewDidLoad()

    self.getCommunities()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func getUsers() {


        Alamofire.request(.GET, "url", parameters: parameters)
            .responseJSON {response in
                if let json = response.result.value {
                    let jsonObj = SwiftyJSON.JSON(json)

                    if let data = jsonObj.arrayValue as [SwiftyJSON.JSON]? {
                        self.tableData = data
                        self.collectionView.reloadData()
                        self.loadingView.hidden = true
                    }
                }
        }

}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.tableData.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: UserViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("userCell", forIndexPath: indexPath) as! UserViewCell

    let rowData = tableData[indexPath.row]

    if let userName = rowData["name"].string {
        cell.userName.text = userName
    }

    if let userAvatar = rowData["background"].string {
        let url = NSURL(string: userAvatar)
        cell.userAvatar.clipsToBounds = true
        cell.userAvatar.contentMode = .ScaleAspectFill
        cell.userAvatar.hnk_setImageFromURL(url!)
    }

    cell.backgroundColor = UIColor.whiteColor()

    return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let cell: UserViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("userCell", forIndexPath: indexPath) as! UserViewCell

    let rowData = tableData[indexPath.row]
    let userName = rowData["name"].string
    let userId = rowData["id"].int


    selectedUsers.append(rowData[indexPath.row])

    print("Cell \(userId) \(userName) selected")
}

}

1 个答案:

答案 0 :(得分:0)

    override func viewDidLoad() {
        super.viewDidLoad()

        collection.dataSource = self
        collection.delegate = self
        collection.allowsMultipleSelection = true

        self.getCommunities()
    }

您应该可以使用此选项进行多项选择。