通过点击表视图中的单元格以及如何知道哪些单元格已选中或未选中,选中/取消选中复选框 [英] check / uncheck the check box by tapping the cell in table view and how to know which cell has checked or unchecked
问题描述
我是ios swift 2.2的新手。我试图创建一个表视图与自定义单元格xib。我填充了一些数据在我的表视图。我还添加了一个自定义复选框按钮。我为该复选框按钮创建单独的类。现在当我在我的customcell.xib只点击我的按钮。但是当我点击我的单元格,我的复选框没有改变。我需要有两个。当我点击我的按钮,它应该改变为检查和取消选择图像。当我点击我的单元格,我需要更改我的按钮以检查或取消选中图像
当我向下滚动并再次回到顶部,我的检查图像自动chnaged to normalcheck box。
我需要做一些操作,所以为此。当我点击任何单元格我的复选框应该检查和取消选中。我需要知道哪个行单元格检查图像。
这里是我的自定义复选框类:
import UIKit
class CheckBoxButton:UIButton {
// Images
let checkedImage = UIImage CheckBoxChecked)!作为UIImage
让uncheckedImage = UIImage(命名为:CheckBoxUnChecked)! as UIImage
// Bool属性
var isChecked:Bool = false {
didSet {
if isChecked == true {
self.setImage(checkedImage ,forState:.Normal)
} else {
self.setImage(uncheckedImage,forState:.Normal)
}
}
}
$ b b override func awakeFromNib(){
self.addTarget(self,action:#selector(CheckBoxButton.buttonClicked(_ :)),forControlEvents:UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender:UIButton){
if sender == self {
if isChecked == true {
isChecked = false
} else {
isChecked = true
}
}
}
}
Cutom cell.xib类:
import UIKit
$ b b class FavCell:UITableViewCell {
@IBOutlet weak var FLabel1:UILabel!
@IBOutlet weak var FLabel2:UILabel!
@IBOutlet weak var复选框:CheckBoxButton!
override func awakeFromNib(){
super.awakeFromNib()
//初始化代码
}
@IBAction func checkboxpress(sender:AnyObject){
}
}
my viewcontroller.swift
import UIKit
class FavVC:UIViewController {
@IBOutlet weak var FavTableView:UITableView!
// var FData = [FavouritesData]()
var arrDict:NSMutableArray = []
let cellSpacingHeight:CGFloat = 5 // cell表格视图中每个单元格的间距
override func viewDidLoad(){
super.viewDidLoad()
self.jsonParsingFromURL()
let nib = UINib(nibName:FavCell,bundle:nil)
FavTableView.registerNib(nib,forCellReuseIdentifier:FCell)
} b $ b // web服务方法
func jsonParsingFromURL()
{
// let token = NSUserDefaults.standardUserDefaults()。valueForKey(access_token)as? String
let url = NSURL(string:som url)
let session = NSURLSession.sharedSession()
let request = NSURLRequest URL:url!)
let dataTask = session.dataTaskWithRequest(request){(data:NSData?,response:NSURLResponse ?, error:NSError?) - >无效
// print(done,error:\(error))
如果错误== nil
{
dispatch_async dispatch_get_main_queue())
{
self.arrDict =(try!NSJSONSerialization.JSONObjectWithData(data !, options:NSJSONReadingOptions.MutableContainers))as! NSMutableArray
if(self.arrDict.count> 0)
{
self.FavTableView.reloadData()
}
}
}
}
dataTask.resume()
}
func numberOfSectionsInTableView(tableView:UITableView) - > Int
{
// return self.FData.count
return self.arrDict.count
}
//行数
func tableView(tableView:UITableView,numberOfRowsInSection section:Int) - > int
{
return 1
}
//每个单元格的高度
func tableView(tableView:UITableView,heightForHeaderInSection section:Int) CGFloat
{
return cellSpacingHeight
}
func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) - > UITableViewCell
{
让单元格:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier(FCell)as! FavCell
cell.FLabel1.text = arrDict [indexPath.section] .valueForKey(favourite_name)as? String
cell.FLabel2.text = arrDict [indexPath.section] .valueForKey(favourite_address)as? String
return cell
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处理任何资源可以重新创建。
}
请帮助我。
提前感谢
如@El Capitan所述,为了解决您的问题, didSelectRowAtIndexPath
方法来更改其状态。您的代码应该看起来像这样:
//声明一个存储检查行的变量。 UITableViewCell在你上下滚动的时候出队和恢复,所以最好存储一个被检查的行的引用
var rowsWhichAreChecked = [NSIndexPath]()
func tableView(tableView :UITableView,didSelectRowAtIndexPath indexPath:NSIndexPath){
let cell:FavCell = tableView.cellForRowAtIndexPath(indexPath)as! FavCell
//交叉检查选中行
if(rowsWhichAreChecked.contains(indexPath)== false){
cell.checkBox.isChecked = true
rowsWhichAreChecked.append(indexPath)
} else {
cell.checkBox.isChecked = false
//从rowsWhichAreCheckedArray中删除indexPath
如果let checkedItemIndex = rowsWhichAreChecked.indexOf(indexPath){
rowsWhichAreChecked。 removeAtIndex(checkedItemIndex)
}
}
}
在您的 cellForRowAtIndexPath
中,在滚动视图外的行之前检查的单元格对 rowsWhichAreChecked
数组并相应地设置其状态。
func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) UITableViewCell {
让单元格:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier(FCell)as! FavCell
cell.FLabel1.text = arrDict [indexPath.section] .valueForKey(favourite_name)as? String
cell.FLabel2.text = arrDict [indexPath.section] .valueForKey(favourite_address)as? String
if(rowsWhichAreChecked.contains(indexPath)== false){
cell.checkBox.isChecked = true
} else {
cell。 checkBox.isChecked = false
}
}
return cell
}
已编辑回答
我已经让您的代码工作,但我不得不对您的Checkbox类和ViewController
Checkbox.swift
class CheckBoxButton:UIButton {
// Images
let checkedImage = UIImage(命名为:CheckBoxChecked)!作为UIImage
让uncheckedImage = UIImage(命名为:CheckBoxUnChecked)! as UIImage
// Bool属性
var isChecked:Bool = false {
didSet {
if isChecked == true {
self.setImage(uncheckedImage ,forState:.Normal)
} else {
self.setImage(checkedImage,forState:.Normal)
}
}
}
$ b b override func awakeFromNib(){
self.userInteractionEnabled = false
// self.addTarget(self,action:#selector(CheckBoxButton.buttonClicked(_ :)),forControlEvents:UIControlEvents.TouchUpInside)
// self.isChecked = false
}
func buttonClicked(sender:UIButton){
if sender == self {
if isChecked == true {
isChecked = false
} else {
isChecked = true
}
}
}
}
ViewController.swift
b $ bclass FavVC:UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var FavTableView:UITableView!
var rowsWhichAreChecked = [NSIndexPath]()
// var FData = [FavouritesData]()
var arrDict:NSMutableArray = []
let cellSpacingHeight:CGFloat = 5 //表格视图中每个单元格的单元格间距
override func viewDidLoad(){
self .FavTableView.delegate = self
self.FavTableView.dataSource = self
super.viewDidLoad()
self.jsonParsingFromURL()
let nib = UINib(nibName:FavCell,bundle:nil)
FavTableView.registerNib(nib,forCellReuseIdentifier:FCell)
}
b $ b // web服务方法
func jsonParsingFromURL()
{
// let token = NSUserDefaults.standardUserDefaults()。valueForKey(access_token)as? String
let url = NSURL(string:some url)
let session = NSURLSession.sharedSession()
let request = NSURLRequest URL:url!)
let dataTask = session.dataTaskWithRequest(request){(data:NSData?,response:NSURLResponse ?, error:NSError?) - >无效
// print(done,error:\(error))
如果错误== nil
{
dispatch_async dispatch_get_main_queue())
{
self.arrDict =(try!NSJSONSerialization.JSONObjectWithData(data !, options:NSJSONReadingOptions.MutableContainers))as! NSMutableArray
if(self.arrDict.count> 0)
{
self.FavTableView.reloadData()
}
}
}
}
dataTask.resume()
//
//让StringUrl =http+ token!
// let url:NSURL = NSURL(string:StringUrl)!
// if let JSONData = NSData(contentsOfURL:url)
// {
//如果let json =(try?NSJSONSerialization.JSONObjectWithData(JSONData,options: )) NSDictionary
// {
// json中的值
// {
// self.FData.append()
//}
//如果let reposArray = json [data] as? [NSDictionary]
// {
//
//在reposArray中的项目
// {
// let itemObj = item as?字典< String,AnyObject>
//
//让b_type = itemObj![business_type]?valueForKey(type)
//
// //self.Resultcount.text = \(b_type?.count)Results
//
// if(b_type as?String ==Taxis)
// {
//
// self.FData.append(FavouritesData(json:item))
//
//}
//}
//}
//}
//}
}
func numberOfSectionsInTableView(tableView:UITableView) - > Int
{
// return self.FData.count
return self.arrDict.count
}
//行数
func tableView(tableView:UITableView,numberOfRowsInSection section:Int) - > int
{
return 1
}
//每个单元格的高度
func tableView(tableView:UITableView,heightForHeaderInSection section:Int) CGFloat
{
return cellSpacingHeight
}
func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) - > UITableViewCell
{
让单元格:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier(FCell)as! FavCell
cell.FLabel1.text = arrDict [indexPath.section] .valueForKey(favourite_name)as? String
cell.FLabel2.text = arrDict [indexPath.section] .valueForKey(favourite_address)as? String
let isRowChecked = rowsWhichAreChecked.contains(indexPath)
if(isRowChecked == true)
{
cell.checkbox.isChecked = true
cell.checkbox.buttonClicked(cell.checkbox)
} else {
cell.checkbox.isChecked = false
cell.checkbox.buttonClicked(cell.checkbox)
}
return cell
}
func tableView(tableView:UITableView,didSelectRowAtIndexPath indexPath:NSIndexPath){
let cell:FavCell = tableView.cellForRowAtIndexPath )as! FavCell
//交叉检查选中行
if(rowsWhichAreChecked.contains(indexPath)== false){
cell.checkbox.isChecked = true
cell.checkbox.buttonClicked cell.checkbox)
rowsWhichAreChecked.append(indexPath)
} else {
cell.checkbox.isChecked = false
cell.checkbox.buttonClicked(cell.checkbox)
//从rowsWhichAreCheckedArray中删除indexPath
如果let checkedItemIndex = rowsWhichAreChecked.indexOf(indexPath){
rowsWhichAreChecked.removeAtIndex(checkedItemIndex)
}
}
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处理可以重新创建的任何资源。
}
}
i am new to ios swift 2.2 . I tried to create one table view with custom cell xib. and i am populating some data in my table view. And also i added one custom check box button. And i am creating separate class for that check box button. Now when i click only on my button in my customcell.xib .But when i tap on my cell, my check box are not changing. i need to have both. When i click on my button it should change to check and uncheck image. When i tap on my cell also i need to change my button to check or uncheck image
And when i scroll down and again come back to top, my checked images are automatically chnaged to normalcheck box.
i need to do some action , so for that. When i tap on any cell my check box should check and uncheck.And alos i need to know which row cell has checked image . So that i can perform some action for my checked image row cell alone.
here is my custom check box class:
import UIKit class CheckBoxButton: UIButton { // Images let checkedImage = UIImage(named: "CheckBoxChecked")! as UIImage let uncheckedImage = UIImage(named: "CheckBoxUnChecked")! as UIImage // Bool property var isChecked: Bool = false { didSet{ if isChecked == true { self.setImage(checkedImage, forState: .Normal) } else { self.setImage(uncheckedImage, forState: .Normal) } } } override func awakeFromNib() { self.addTarget(self, action: #selector(CheckBoxButton.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.isChecked = false } func buttonClicked(sender: UIButton) { if sender == self { if isChecked == true { isChecked = false } else { isChecked = true } } } }
Cutom cell.xib class:
import UIKit class FavCell: UITableViewCell { @IBOutlet weak var FLabel1: UILabel! @IBOutlet weak var FLabel2: UILabel! @IBOutlet weak var checkbox: CheckBoxButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBAction func checkboxpress(sender: AnyObject) { } }
my
viewcontroller.swift
import UIKit class FavVC: UIViewController { @IBOutlet weak var FavTableView: UITableView! //var FData = [FavouritesData]() var arrDict :NSMutableArray=[] let cellSpacingHeight: CGFloat = 5 // cell spacing from each cell in table view override func viewDidLoad() { super.viewDidLoad() self.jsonParsingFromURL() let nib = UINib(nibName:"FavCell", bundle: nil) FavTableView.registerNib(nib, forCellReuseIdentifier: "FCell") } // web services method func jsonParsingFromURL () { // let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as? String let url = NSURL(string: "som url") let session = NSURLSession.sharedSession() let request = NSURLRequest(URL: url!) let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in // print("done, error: \(error)") if error == nil { dispatch_async(dispatch_get_main_queue()) { self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray if (self.arrDict.count>0) { self.FavTableView.reloadData() } } } } dataTask.resume() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return self.FData.count return self.arrDict.count } // number of rows func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } // height for each cell func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return cellSpacingHeight } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier("FCell") as! FavCell cell.FLabel1.text=arrDict[indexPath.section] .valueForKey("favourite_name") as? String cell.FLabel2.text=arrDict[indexPath.section] .valueForKey("favourite_address") as? String return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }
please help me out.
Thanks in advance
解决方案In order to solve your issue, as @El Capitan mentioned, you will need to use the
didSelectRowAtIndexPath
method to change its states. Your codes should look something along the lines of this:// Declare a variable which stores checked rows. UITableViewCell gets dequeued and restored as you scroll up and down, so it is best to store a reference of rows which has been checked var rowsWhichAreChecked = [NSIndexPath]() func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell:FavCell = tableView.cellForRowAtIndexPath(indexPath) as! FavCell // cross checking for checked rows if(rowsWhichAreChecked.contains(indexPath) == false){ cell.checkBox.isChecked = true rowsWhichAreChecked.append(indexPath) }else{ cell.checkBox.isChecked = false // remove the indexPath from rowsWhichAreCheckedArray if let checkedItemIndex = rowsWhichAreChecked.indexOf(indexPath){ rowsWhichAreChecked.removeAtIndex(checkedItemIndex) } } }
To redisplay cells which have been checked before after scrolling the rows out of view, at your
cellForRowAtIndexPath
, perform the same checking againstrowsWhichAreChecked
array and set its states accordingly.func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier("FCell") as! FavCell cell.FLabel1.text=arrDict[indexPath.section] .valueForKey("favourite_name") as? String cell.FLabel2.text=arrDict[indexPath.section] .valueForKey("favourite_address") as? String if(rowsWhichAreChecked.contains(indexPath) == false){ cell.checkBox.isChecked = true }else{ cell.checkBox.isChecked = false } } return cell }
EDITED ANSWER
I have got your code to work but I had to make some modifications to your Checkbox class and ViewController
Checkbox.swift
class CheckBoxButton: UIButton { // Images let checkedImage = UIImage(named: "CheckBoxChecked")! as UIImage let uncheckedImage = UIImage(named: "CheckBoxUnChecked")! as UIImage // Bool property var isChecked: Bool = false { didSet{ if isChecked == true { self.setImage(uncheckedImage, forState: .Normal) } else { self.setImage(checkedImage, forState: .Normal) } } } override func awakeFromNib() { self.userInteractionEnabled = false // self.addTarget(self, action: #selector(CheckBoxButton.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside) // self.isChecked = false } func buttonClicked(sender: UIButton) { if sender == self { if isChecked == true { isChecked = false } else { isChecked = true } } } }
ViewController.swift
class FavVC: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var FavTableView: UITableView! var rowsWhichAreChecked = [NSIndexPath]() //var FData = [FavouritesData]() var arrDict :NSMutableArray=[] let cellSpacingHeight: CGFloat = 5 // cell spacing from each cell in table view override func viewDidLoad() { self.FavTableView.delegate = self self.FavTableView.dataSource = self super.viewDidLoad() self.jsonParsingFromURL() let nib = UINib(nibName:"FavCell", bundle: nil) FavTableView.registerNib(nib, forCellReuseIdentifier: "FCell") } // web services method func jsonParsingFromURL () { // let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as? String let url = NSURL(string: "some url") let session = NSURLSession.sharedSession() let request = NSURLRequest(URL: url!) let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in // print("done, error: \(error)") if error == nil { dispatch_async(dispatch_get_main_queue()) { self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray if (self.arrDict.count>0) { self.FavTableView.reloadData() } } } } dataTask.resume() // // let StringUrl = "http"+token! // let url:NSURL = NSURL(string: StringUrl)! // if let JSONData = NSData(contentsOfURL: url) // { // if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary // { // for values in json // { // self.FData.append() // } // if let reposArray = json["data"] as? [NSDictionary] // { // // for item in reposArray // { // let itemObj = item as? Dictionary<String,AnyObject> // // let b_type = itemObj!["business_type"]?.valueForKey("type") // // //self.Resultcount.text = "\(b_type?.count) Results" // // if (b_type as? String == "Taxis") // { // // self.FData.append(FavouritesData(json:item)) // // } // } // } // } // } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return self.FData.count return self.arrDict.count } // number of rows func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } // height for each cell func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return cellSpacingHeight } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier("FCell") as! FavCell cell.FLabel1.text=arrDict[indexPath.section] .valueForKey("favourite_name") as? String cell.FLabel2.text=arrDict[indexPath.section] .valueForKey("favourite_address") as? String let isRowChecked = rowsWhichAreChecked.contains(indexPath) if(isRowChecked == true) { cell.checkbox.isChecked = true cell.checkbox.buttonClicked(cell.checkbox) }else{ cell.checkbox.isChecked = false cell.checkbox.buttonClicked(cell.checkbox) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell:FavCell = tableView.cellForRowAtIndexPath(indexPath) as! FavCell // cross checking for checked rows if(rowsWhichAreChecked.contains(indexPath) == false){ cell.checkbox.isChecked = true cell.checkbox.buttonClicked(cell.checkbox) rowsWhichAreChecked.append(indexPath) }else{ cell.checkbox.isChecked = false cell.checkbox.buttonClicked(cell.checkbox) // remove the indexPath from rowsWhichAreCheckedArray if let checkedItemIndex = rowsWhichAreChecked.indexOf(indexPath){ rowsWhichAreChecked.removeAtIndex(checkedItemIndex) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
这篇关于通过点击表视图中的单元格以及如何知道哪些单元格已选中或未选中,选中/取消选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!