gpt4 book ai didi

ios - 通过点击表格 View 中的单元格来选中/取消选中复选框,以及如何知道哪个单元格已选中或未选中

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:06 25 4
gpt4 key购买 nike

我是 ios swift 2.2 的新手。我试图用自定义单元格 xib 创建一个 TableView 。我正在我的表格 View 中填充一些数据。我还添加了一个自定义复选框按钮。我正在为该复选框按钮创建单独的类。现在,当我只单击我的 customcell.xib 中的按钮时。但是当我点击我的单元格时,我的复选框没有改变。我需要两者兼得。当我点击我的按钮时,它应该更改为选中和取消选中图像。当我点击我的手机时,我还需要更改我的按钮以选中或取消选中图像

当我向下滚动并再次返回顶部时,我选中的图像会自动更改为 normalcheck 框。

我需要采取一些行动,所以为此。当我点击任何单元格时,我的复选框应该选中和取消选中。而且我需要知道哪个行单元格选中了图像。这样我就可以单独对选中的图像行单元格执行一些操作。

这是我的自定义复选框类:

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
}
}
}

}

自定义cell.xib类:

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) {
}



}

我的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.
}

请帮帮我。

提前致谢

最佳答案

为了解决您的问题,如@El Capitan 所述,您需要使用 didSelectRowAtIndexPath 方法来更改其状态。你的代码应该看起来像这样:

// 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)
}
}
}

要在将行滚动出 View 后重新显示之前检查过的单元格,请在您的 cellForRowAtIndexPath 中,对 rowsWhichAreChecked 数组执行相同的检查并相应地设置其状态。

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
}

编辑后的答案

我已经让您的代码正常工作,但我必须对您的 Checkbox 类和 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.
}

}

关于ios - 通过点击表格 View 中的单元格来选中/取消选中复选框,以及如何知道哪个单元格已选中或未选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com