Ios Swift-使用选中按钮保存tableviewcells;套用;按钮点击
我在tableview中显示饮料类别。在每个单元格中显示类别名称,并有一个复选框按钮。在按钮上单击复选框,图像从“选中的图像”更改为“未选中的图像”Ios Swift-使用选中按钮保存tableviewcells;套用;按钮点击,ios,swift,uitableview,button,checkbox,Ios,Swift,Uitableview,Button,Checkbox,我在tableview中显示饮料类别。在每个单元格中显示类别名称,并有一个复选框按钮。在按钮上单击复选框,图像从“选中的图像”更改为“未选中的图像” 我想区分哪些单元格在用户按下“应用”按钮时显示“选中图像”。然后从每个选定单元格(其按钮显示“checked image”图像的单元格)获取categoryLabel,并将其保存在数组中 复选框类: class CheckBox: UIButton { override func awakeFromNib() {
我想区分哪些单元格在用户按下“应用”按钮时显示“选中图像”。然后从每个选定单元格(其按钮显示“checked image”图像的单元格)获取categoryLabel,并将其保存在数组中 复选框类:
class CheckBox: UIButton
{
override func awakeFromNib()
{
let checkedImage = UIImage(named: "checked-image")! as UIImage
let uncheckedImage = UIImage(named: "unchecked-image")! as UIImage
self.setImage(uncheckedImage, for: .normal)
self.setImage(checkedImage, for: .selected)
self.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.isSelected = true
}
@objc func buttonClicked(sender: UIButton)
{
if sender == self {
sender.isSelected = !sender.isSelected
}
}
}
TableView:
class FilterViewController: UIViewController {
var categories = [Category]()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var applyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getCategories()
}
@IBAction func applyButtonClicked(_ sender: UIButton) {
print("Filter applied")
// save checked buttons
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.categories = try JSONDecoder().decode(Categories.self, from: data!).drinks
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
}
extension FilterViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryCell
cell.categoryLabel.text = categories[indexPath.row].strCategory
cell.styleButton()
return cell
}
}
类别模型:
struct Categories:Decodable {
var drinks: [Category]
}
struct Category:Decodable {
var strCategory: String
}
饮料型号:
struct Response:Decodable {
var drinks: [Drink]
}
struct Drink:Decodable {
var strDrink: String
var strDrinkThumb: String
}
类别:
class CategoryCell: UITableViewCell {
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var checkBoxButton: CheckBox!
}
我的应用程序:
像这样重新排列您的代码
import UIKit
struct Categories: Codable {
let drinks: [Drink]
}
// MARK: - Drink
struct Drink: Codable {
let strCategory: String
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate{
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var btnDone: UIButton!
var datas = [[String : Any]]()
var category = [Drink]()
override func viewDidLoad() {
super.viewDidLoad()
self.getCategories()
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.category = try JSONDecoder().decode(Categories.self, from: data!).drinks
for i in 0..<self.category.count
{
self.datas.append(["name":self.category[i].strCategory, "status":"0"])
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
@IBAction func btnDone(_ sender: Any) {
var selectedCatgry = [String]()
for i in 0..<datas.count
{
let rowVal = datas[i]
if rowVal["status"] as! String == "1"{
selectedCatgry.append(rowVal["name"] as! String)
}
}
print(selectedCatgry)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! cell
let val = datas[indexPath.row]
cell.descriptionName.text = (val["name"] as! String)
if (val["status"] as! String) == "1"{
cell.btnSelect.setImage(UIImage(systemName: "circle.fill"), for: .normal)
}else{
cell.btnSelect.setImage(UIImage(systemName: "circle"), for: .normal)
}
cell.btnSelect.addTarget(self, action: #selector(subscribeTapped(_:)), for: .touchUpInside)
cell.btnSelect.tag = indexPath.row
return cell
}
@objc func subscribeTapped(_ sender: UIButton){
var sel = datas[sender.tag]
datas.remove(at: sender.tag)
if sel["status"] as! String == "1"{
sel.updateValue("0", forKey: "status")
}else{
sel.updateValue("1", forKey: "status")
}
datas.insert(sel, at: sender.tag)
tableView.reloadData()
}
}
class cell: UITableViewCell {
@IBOutlet weak var btnSelect: UIButton!
@IBOutlet weak var descriptionName: UILabel!
}
导入UIKit
结构类别:可编码{
让我们喝一杯:[喝一杯]
}
//马克:喝酒
结构:可编码{
让strCategory:String
}
类ViewController:UIViewController、UITableViewDataSource、UITableViewDelegate、UIGestureRecognitizerDelegate{
@IBVAR表格视图:UITableView!
@IBOUTLE弱var btnDone:UIButton!
变量数据=[[String:Any]]()
变量类别=[饮料]()
重写func viewDidLoad(){
super.viewDidLoad()
self.getCategories()
}
func getCategories(){
让url=url(字符串:https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(带有:url!){(数据、响应、错误)在
如果错误==nil{
做{
self.category=尝试JSONDecoder().decode(Categories.self,from:data!)。饮料
对于0..UITableViewCell中的i{
让cell=tableView.dequeueReusableCell(带有标识符:“cell”,for:indexPath)作为!cell
设val=datas[indexPath.row]
cell.descriptionName.text=(val[“name”]as!String)
如果(val[“status”]as!String)=“1”{
cell.btnSelect.setImage(UIImage(系统名:“circle.fill”),用于:。正常)
}否则{
cell.btnSelect.setImage(UIImage(系统名称:“圆圈”),用于:。正常)
}
cell.btselect.addTarget(self,action:#选择器(subscribeTapped(:)),for:.touchUpInside)
cell.btnSelect.tag=indexPath.row
返回单元
}
@objc func subscribeTapped(uu发送方:ui按钮){
var sel=datas[sender.tag]
datas.remove(位于:sender.tag)
如果选择[“状态”]为!字符串==“1”{
选择更新值(“0”,分叉:“状态”)
}否则{
选择更新值(“1”,分叉:“状态”)
}
插入数据(sel,at:sender.tag)
tableView.reloadData()
}
}
类别单元格:UITableViewCell{
@IBOutlet弱var B选择:UIButton!
@IBVAR描述名称:UILabel!
}
像这样重新排列您的代码
import UIKit
struct Categories: Codable {
let drinks: [Drink]
}
// MARK: - Drink
struct Drink: Codable {
let strCategory: String
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate{
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var btnDone: UIButton!
var datas = [[String : Any]]()
var category = [Drink]()
override func viewDidLoad() {
super.viewDidLoad()
self.getCategories()
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.category = try JSONDecoder().decode(Categories.self, from: data!).drinks
for i in 0..<self.category.count
{
self.datas.append(["name":self.category[i].strCategory, "status":"0"])
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
@IBAction func btnDone(_ sender: Any) {
var selectedCatgry = [String]()
for i in 0..<datas.count
{
let rowVal = datas[i]
if rowVal["status"] as! String == "1"{
selectedCatgry.append(rowVal["name"] as! String)
}
}
print(selectedCatgry)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! cell
let val = datas[indexPath.row]
cell.descriptionName.text = (val["name"] as! String)
if (val["status"] as! String) == "1"{
cell.btnSelect.setImage(UIImage(systemName: "circle.fill"), for: .normal)
}else{
cell.btnSelect.setImage(UIImage(systemName: "circle"), for: .normal)
}
cell.btnSelect.addTarget(self, action: #selector(subscribeTapped(_:)), for: .touchUpInside)
cell.btnSelect.tag = indexPath.row
return cell
}
@objc func subscribeTapped(_ sender: UIButton){
var sel = datas[sender.tag]
datas.remove(at: sender.tag)
if sel["status"] as! String == "1"{
sel.updateValue("0", forKey: "status")
}else{
sel.updateValue("1", forKey: "status")
}
datas.insert(sel, at: sender.tag)
tableView.reloadData()
}
}
class cell: UITableViewCell {
@IBOutlet weak var btnSelect: UIButton!
@IBOutlet weak var descriptionName: UILabel!
}
导入UIKit
结构类别:可编码{
让我们喝一杯:[喝一杯]
}
//马克:喝酒
结构:可编码{
让strCategory:String
}
类ViewController:UIViewController、UITableViewDataSource、UITableViewDelegate、UIGestureRecognitizerDelegate{
@IBVAR表格视图:UITableView!
@IBOUTLE弱var btnDone:UIButton!
变量数据=[[String:Any]]()
变量类别=[饮料]()
重写func viewDidLoad(){
super.viewDidLoad()
self.getCategories()
}
func getCategories(){
让url=url(字符串:https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(带有:url!){(数据、响应、错误)在
如果错误==nil{
做{
self.category=尝试JSONDecoder().decode(Categories.self,from:data!)。饮料
对于0..UITableViewCell中的i{
让cell=tableView.dequeueReusableCell(带有标识符:“cell”,for:indexPath)作为!cell
设val=datas[indexPath.row]
cell.descriptionName.text=(val[“name”]as!String)
如果(val[“status”]as!String)=“1”{
cell.btnSelect.setImage(UIImage(系统名:“circle.fill”),用于:。正常)
}否则{
cell.btnSelect.setImage(UIImage(系统名称:“圆圈”),用于:。正常)
}
cell.btselect.addTarget(self,action:#选择器(subscribeTapped(:)),for:.touchUpInside)
cell.btnSelect.tag=indexPath.row
返回单元
}
@objc func subscribeTapped(uu发送方:ui按钮){
var sel=datas[sender.tag]
datas.remove(位于:sender.tag)
如果选择[“状态”]为!字符串==“1”{
选择更新值(“0”,分叉:“状态”)
}否则{
选择更新值(“1”,分叉:“状态”)
}
插入数据(sel,at:sender.tag)
tableView.reloadData()
}
}
类别单元格:UITableViewCell{
@IBOutlet弱var B选择:UIButton!
@IBVAR描述名称:UILabel!
}
请尝试以下代码:
复选框类:
class CheckBox: UIButton
{
override func awakeFromNib()
{
let checkedImage = UIImage(named: "checked-image")! as UIImage
let uncheckedImage = UIImage(named: "unchecked-image")! as UIImage
self.setImage(uncheckedImage, for: .normal)
self.setImage(checkedImage, for: .selected)
self.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.isSelected = true
}
@objc func buttonClicked(sender: UIButton)
{
if sender == self {
sender.isSelected = !sender.isSelected
}
}
}
class FilterViewController: UIViewController
{
var categories = [Category]()
var selectedCategories = [String]()
var selectedCategories : NSMutableArray = NSMutableArray()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var applyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getCategories()
}
@IBAction func applyButtonClicked(_ sender: UIButton) {
print("Filter applied")
// save checked buttons
print("Selected Categories =", selectedCategories)
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.categories = try JSONDecoder().decode(Categories.self, from: data!).drinks
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
}
extension FilterViewController: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryCell
cell.categoryLabel.text = categories[indexPath.row].strCategory
cell.styleButton()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if selectedCategories.contains(categories[indexPath.row].strCategory) {
selectedCategories.remove(categories[indexPath.row].strCategory)
}else{
selectedCategories.add(categories[indexPath.row].strCategory)
}
}
}
Tableview类:
class CheckBox: UIButton
{
override func awakeFromNib()
{
let checkedImage = UIImage(named: "checked-image")! as UIImage
let uncheckedImage = UIImage(named: "unchecked-image")! as UIImage
self.setImage(uncheckedImage, for: .normal)
self.setImage(checkedImage, for: .selected)
self.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.isSelected = true
}
@objc func buttonClicked(sender: UIButton)
{
if sender == self {
sender.isSelected = !sender.isSelected
}
}
}
class FilterViewController: UIViewController
{
var categories = [Category]()
var selectedCategories = [String]()
var selectedCategories : NSMutableArray = NSMutableArray()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var applyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getCategories()
}
@IBAction func applyButtonClicked(_ sender: UIButton) {
print("Filter applied")
// save checked buttons
print("Selected Categories =", selectedCategories)
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.categories = try JSONDecoder().decode(Categories.self, from: data!).drinks
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
}
extension FilterViewController: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryCell
cell.categoryLabel.text = categories[indexPath.row].strCategory
cell.styleButton()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if selectedCategories.contains(categories[indexPath.row].strCategory) {
selectedCategories.remove(categories[indexPath.row].strCategory)
}else{
selectedCategories.add(categories[indexPath.row].strCategory)
}
}
}
请尝试以下代码: 复选框类:
class CheckBox: UIButton
{
override func awakeFromNib()
{
let checkedImage = UIImage(named: "checked-image")! as UIImage
let uncheckedImage = UIImage(named: "unchecked-image")! as UIImage
self.setImage(uncheckedImage, for: .normal)
self.setImage(checkedImage, for: .selected)
self.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.isSelected = true
}
@objc func buttonClicked(sender: UIButton)
{
if sender == self {
sender.isSelected = !sender.isSelected
}
}
}
class FilterViewController: UIViewController
{
var categories = [Category]()
var selectedCategories = [String]()
var selectedCategories : NSMutableArray = NSMutableArray()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var applyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getCategories()
}
@IBAction func applyButtonClicked(_ sender: UIButton) {
print("Filter applied")
// save checked buttons
print("Selected Categories =", selectedCategories)
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.categories = try JSONDecoder().decode(Categories.self, from: data!).drinks
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
}
extension FilterViewController: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryCell
cell.categoryLabel.text = categories[indexPath.row].strCategory
cell.styleButton()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if selectedCategories.contains(categories[indexPath.row].strCategory) {
selectedCategories.remove(categories[indexPath.row].strCategory)
}else{
selectedCategories.add(categories[indexPath.row].strCategory)
}
}
}
Tableview类:
class CheckBox: UIButton
{
override func awakeFromNib()
{
let checkedImage = UIImage(named: "checked-image")! as UIImage
let uncheckedImage = UIImage(named: "unchecked-image")! as UIImage
self.setImage(uncheckedImage, for: .normal)
self.setImage(checkedImage, for: .selected)
self.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.isSelected = true
}
@objc func buttonClicked(sender: UIButton)
{
if sender == self {
sender.isSelected = !sender.isSelected
}
}
}
class FilterViewController: UIViewController
{
var categories = [Category]()
var selectedCategories = [String]()
var selectedCategories : NSMutableArray = NSMutableArray()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var applyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getCategories()
}
@IBAction func applyButtonClicked(_ sender: UIButton) {
print("Filter applied")
// save checked buttons
print("Selected Categories =", selectedCategories)
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.categories = try JSONDecoder().decode(Categories.self, from: data!).drinks
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
}
extension FilterViewController: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryCell
cell.categoryLabel.text = categories[indexPath.row].strCategory
cell.styleButton()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if selectedCategories.contains(categories[indexPath.row].strCategory) {
selectedCategories.remove(categories[indexPath.row].strCategory)
}else{
selectedCategories.add(categories[indexPath.row].strCategory)
}
}
}
您是否在询问如何在应用程序启动之间保留用户数据/选择?我想区分哪些单元格在用户按下“应用”时显示“选中图像”按钮。然后从每个选定单元格中获取categoryLabel并将其保存在数组中。您是否询问如何在应用程序启动之间保留用户数据/选择?我想区分哪些单元格在用户按下“应用”时显示“选中图像”按钮。然后从每个选定单元格中获取categoryLabel并将其保存在数组中。它不会保存显示“选中图像”的单元格,而是点击cellsOk,您如何选择选中的单元格或具有“选中图像”的单元格?另外,您能否共享单元格。styleButton()代码?它不会保存显示“选中图像”的单元格显示,但点击了cellsOk