I have created a carousel view using UPCarouselFlowLayout and it works well. But when the UIButton in the view is clicked, no action occurs. How do I make it so that when the UIButton is clicked, it calls a particular action?
CollectionViewCell:
class MagicCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var magicview: UIView!
#IBOutlet weak var magicimage: UIImageView!
#IBOutlet weak var magiclabel: UILabel!
#IBOutlet weak var magicbutton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.magicview.isUserInteractionEnabled = true
// Initialization code
DispatchQueue.main.async {
self.magicview.layer.shadowColor = UIColor.gray.cgColor
self.magicview.layer.shadowOpacity = 0.5
self.magicview.layer.shadowOpacity = 10.0
self.magicview.layer.shadowOffset = .zero
self.magicview.layer.shadowPath = UIBezierPath(rect: self.magicview.bounds).cgPath
self.magicview.layer.shouldRasterize = false
}
}
}
Magic1.swift
import UPCarouselFlowLayout
class Magic1: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
#IBOutlet weak var magiccollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
magiccollection.register(UINib.init(nibName: "MagicCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "magiccidentifier")
let floawLayout = UPCarouselFlowLayout()
floawLayout.itemSize = CGSize(width: UIScreen.main.bounds.width - 60.0, height: magiccollection.frame.size.height)
floawLayout.scrollDirection = .horizontal
floawLayout.sideItemScale = 0.8
floawLayout.sideItemAlpha = 1.0
floawLayout.spacingMode = .fixed(spacing: 5.0)
magiccollection.collectionViewLayout = floawLayout
magiccollection.delegate = self
magiccollection.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = sexeducollec.dequeueReusableCell(withReuseIdentifier: "magiccidentifier", for: indexPath) as!MagicCollectionViewCell
if indexPath.row == 0{
cell.magiclabel.text = "Tester title"
cell.sexedimage.image = #imageLiteral(resourceName: "merlin")
}else if indexPath.row == 1{
cell.magiclabel.text = "love is in the air"
}else{
cell.magiclabel.text = "Title - \(indexPath.row + 1)"
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.row == 0{
print("Accio")
}else if indexPath.row == 1{
print("alohamora")
}
}
}
What I'm trying to do is when magicbutton is clicked at indexPath.row == 0 it calls a specific action and when it is clicked at indexPath.row == 1 it calls a specific function.
Try this approach! Also, You can call closure at IBAction
class ViewController: UICollectionViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "magiccidentifier", for: indexPath) as? MagicCollectionViewCell {
switch indexPath.row {
case 0:
cell.onCellTouched = { print("Hi")}
default:
cell.onCellTouched = { print("By") }
}
return cell
}
return UICollectionViewCell()
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item = collectionView.cellForItem(at: indexPath) as? MagicCollectionViewCell
item?.onCellTouched()
}
}
class MagicCollectionViewCell: UICollectionViewCell {
var onCellTouched: () -> Void = { assertionFailure("Cell action didn't set up") }
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = .black
}
}
You are missing an IBAction of your button in MagicCollectionViewCell. So add an action for your button:
#IBAction func buttonAction(_ sender: UIButton) {
}
Related
I have an issue with a collectionView inside a TableVieCell. When i tap on a collectionCell, didSelectItemAt doesn´t get called. I have a button in the collectionCell so i tried to disable the user interaction and enable the contentView userInteraction but it didn't work.
The red rectangle is the tableCell and the blue rectangle is the collecionView insede the table view cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "MedCellWithCollection") as? MedCellWithCollection{
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.white.withAlphaComponent(0.0)
cell.selectedBackgroundView = backgroundView
cell.setMedName(name: self.medCatalog[indexPath.row].nombre, uso: self.medCatalog[indexPath.row].uso , array: self.medCatalog[indexPath.row].enfermedades[0].aplicaciones , index: indexPath.row)
cell.layoutIfNeeded()
cell.layoutSubviews()
cell.setNeedsUpdateConstraints()
cell.updateConstraintsIfNeeded()
return cell
}
}
return UITableViewCell()
}
The tableCell
class MedCellWithCollection: UITableViewCell {
//Outlets
#IBOutlet weak var medText: UILabel!
#IBOutlet weak var uso: UILabel!
#IBOutlet weak var arrowIcon: UIImageView!
#IBOutlet weak var CollectionView: UICollectionView!
//Variables
var dosesType:[Aplicacion]?
override func awakeFromNib() {
super.awakeFromNib()
self.collectionViewSetUp()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setMedName(name: String, uso: String, array: [Aplicacion], index: Int){
self.medText.text = name
self.uso.text = uso
self.dosesType = array
self.CollectionView.reloadData()
}
}
extension MedCellWithCollection: UICollectionViewDataSource, UICollectionViewDelegate{
func collectionViewSetUp(){
self.CollectionView.delegate = self
self.CollectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dosesType?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "doseColletion", for: indexPath as IndexPath) as? DoseCollection {
cell.setButtonConfig(doseType: self.dosesType![indexPath.row].metodo , index: indexPath.row)
return cell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("tapped")
}
}
CollectionCell
import UIKit
class DoseCollection: UICollectionViewCell {
//Outlets
#IBOutlet weak var Button: Button!
//Variables
let constants = Constants()
func setButtonConfig(doseType: String, index: Int){
self.Button.titleLabel?.text = doseType
self.Button.backgroundColor = constants.COLOR_ARRAY[index]
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func layoutIfNeeded() {
super.layoutIfNeeded()
}
}
Potential Solutions:
1) Should be Single Selection for tableView selection property, programmatically it can be done by tableView.allowsSelection = true
2) The class is not the UITableViewDelegate for that table view, though UITableViewController is supposed to set that automatically.
tableView?.delegate = self
3) If the problem arise with UITapGestureRecognizer:
let tap = UITapGestureRecognizer(target: self, action:Selector("dismissKeyboard"))
view.addGestureRecognizer(tap)
tap.cancelsTouchesInView = false
BOL :)
In my case, I want to change the background of the button in other words the background of the cell in the collection view:
class CustomCVCell: UICollectionViewCell {
override var isSelected: Bool {
didSet {
grayBackgroundViewWithImage.image =
isSelected ? UIImage(named: "") : UIImage()
}
}
In the main class where the collection view is stored create this variable:
class CustomViewController: UIViewController {
///save the indexPath of last selected cell
private var lastSelectedIndexPath: IndexPath? }
In viewDidLoad() set this value to false:
customCollectionView.allowsMultipleSelection = false
Further code in data source. In my case, the first cell should be is selected:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCVCell.cellID(),
for: indexPath) as! CustomCVCell
if indexPath.row == 0 {
lastSelectedIndexPath = indexPath
cell.isSelected = true
}
//update last select state from lastSelectedIndexPath
cell.isSelected = (lastSelectedIndexPath == indexPath)
return cell
}
Further code in the delegate:
///UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard lastSelectedIndexPath != indexPath else { return }
if let index = lastSelectedIndexPath {
let cell = collectionView.cellForItem(at: index) as! CustomCVCell
cell.isSelected = false
}
let cell = collectionView.cellForItem(at: indexPath) as! CustomCVCell
cell.isSelected = true
lastSelectedIndexPath = indexPath
}
I'm working on a requirement where I need to add the items in a UICollectionView dynamically.
Here is my code of ViewController
import UIKit
class ViewController: UIViewController {
enum Direction {
case Horizonatal
case Verticle
}
var enumDirection: Direction = .Verticle
var direction = "Verticle"
var SectionsAndRows = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
SectionsAndRows.append(4)
SectionsAndRows.append(3)
SectionsAndRows.append(2)
SectionsAndRows.append(1)
//SectionsAndRows.append(5)
}
#IBOutlet var gridCollectionView: UICollectionView! {
didSet {
gridCollectionView.bounces = false
}
}
#IBOutlet var gridLayout: UICollectionViewFlowLayout! {
didSet {
//gridLayout.stickyRowsCount = 0
gridLayout.scrollDirection = .horizontal
//gridLayout.stickyColumnsCount = 0
gridLayout.minimumLineSpacing = 5
gridLayout.minimumInteritemSpacing = 5
}
}
}
// MARK: - Collection view data source and delegate methods
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return SectionsAndRows.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(SectionsAndRows[section])
return SectionsAndRows[section]
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseID, for: indexPath) as? CollectionViewCell else {
return UICollectionViewCell()
}
print("Current Section ==\(indexPath.section) CurrentRow ===\(indexPath.row) and its rows count ==\(SectionsAndRows[indexPath.section])")
cell.titleLabel.text = ""
cell.btn.addTarget(self, action: #selector(handleAdd(sender:)), for: .touchUpInside)
cell.btn.tag = (indexPath.section * 1000) + indexPath.row
if enumDirection == .Verticle {
if indexPath.section == SectionsAndRows.count - 1 {
cell.btn.setTitle("+", for: .normal)
} else {
cell.btn.setTitle("\(indexPath)", for: .normal)
}
}
return cell
}
#objc func handleAdd(sender: UIButton) {
// Perform some opration
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
CollectionViewCell.swift
import UIKit
class CollectionViewCell: UICollectionViewCell {
static let reuseID = "CollectionViewCell"
#IBOutlet weak var btn: UIButton!
#IBOutlet weak var titleLabel: UILabel!
}
If you run the code, it will show a Collection of 1 row and 1 column in each row. If you uncomment the last line of viewDidLoad() (SectionsAndRows.append(5)) function, then it works fine.
My observation is that the last section of the CollectionView will have the highest number of a column. Is that correct or is this a bug of a CollectionView?
I am trying to make a collectionView header become hidden when a button is tapped but I cant seem to access this property from inside of the IBAction function.
button function
var buttonPressed:Bool = true
#IBAction func changeView(_ sender: Any) {
if buttonPressed{
UIView.animate(withDuration: 0.05){
self.buttonPressed = !self.buttonPressed
print("Ive been expanded")
}
}
else{
UIView.animate(withDuration: 0.05){
self.buttonPressed = !self.buttonPressed
}
}
}
}
Code in its entirety
import UIKit
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
#IBOutlet weak var animateCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
animateCollectionView.dataSource = self
animateCollectionView.delegate = self
animateCollectionView.backgroundColor = UIColor.blue
animateCollectionView.frame = CGRect(x: 0, y: 100, width: 600, height: 1000)
let layout = animateCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.sectionHeadersPinToVisibleBounds = true
self.view.sendSubview(toBack: self.animateCollectionView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 200
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.animateCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! customCell
cell.cellLabel.text = "\(indexPath.item)"
cell.backgroundColor = UIColor.orange
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// returning the search bar for header
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerCell", for: indexPath) as! customHeader
header.backgroundColor = UIColor.purple
return header
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
// if section is above search bar we need to make its height 0
if section == 0 {
return CGSize(width: 0, height: 0)
}
// for section header i.e. actual search bar
return CGSize(width: animateCollectionView.frame.width, height: 50)
}
var buttonPressed:Bool = true
#IBAction func changeView(_ sender: Any) {
if buttonPressed{
UIView.animate(withDuration: 0.05){
self.buttonPressed = !self.buttonPressed
print("Ive been expanded")
}
}
else{
UIView.animate(withDuration: 0.05){
}
}
}
}
class customCell :UICollectionViewCell{
#IBOutlet weak var cellLabel: UILabel!
}
class customHeader: UICollectionReusableView{
}
As #SPatel mentioned, set the size to zero.
Then set up a delegate method from the cell to the VC so that the VC knows to invalidate layouts.
For instance:
Cell Class
protocol HideHeaderViewDelegate {
func hideHeaderView(hide: Bool)
}
class HeaderView: UICollectionReusableView {
var delegate: HideHeaderViewDelegate?
#IBOutlet weak var hideButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
}
#IBAction func hideButtonAction(_ sender: Any) {
self.frame.size = CGSize.zero
guard let delegate = delegate else { return }
delegate.hideHeaderView(hide: true)
}
}
View Controller
extension ViewController: HideHeaderView {
func hideHeaderView(hide: Bool) {
if hide == true {
print(hide)
// invalidate your layout here
}
}
}
Don't forget to set the delegate
func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: "headerView", for: indexPath) as! HeaderView
headerView.delegate = self
return headerView
}
The current structure is
firstViewController -> pushViewController(SecondViewController)
-UIViewController ->filename : secondViewController
-UITableView
-UITableViewCell (custom cell) ->filename : secondTableViewCell
-UICollectionView
-UICollectionViewCell (custom cell) ->filename : secondCollectionViewCell
When 'didSelectItemAt' is done in the 'UICollectionView'
I would like to call the 'popviewcontroller' from UIViewController.
And I want to pass the data on the selected item to firstViewController.
but i don't know how
** ViewController **
struct cellStat{
var opened = Bool()
var title = String()
var sectionData = [ItemModel]()
}
//선물 카테고리 리스트 보여주는 모달
class GiftCategoryModalVC: UIViewController {
#IBOutlet weak var tableView: UITableView!
private var categoryTitleModels: [ItemModel] = []
private var giftItemModels: [ItemModel] = []
private var titleCellData: [cellStat] = []
//LIFE CYCLE
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: GiftCategoryTBCell.reusableIdentifier, bundle: nil), forCellReuseIdentifier: GiftCategoryTBCell.reusableIdentifier)
tableView.register(UINib(nibName: GiftCategoryListTBCell.reusableIdentifier, bundle: nil), forCellReuseIdentifier: GiftCategoryListTBCell.reusableIdentifier)
//get gift categofy title
GiftPageAPIService.shared.selectCode(code: "CD005") { (itemModels) in
self.categoryTitleModels = itemModels
itemModels.forEach { (itemModel) in
self.titleCellData.append(cellStat(opened: false, title: itemModel.codeNm!, sectionData: []))
}
self.tableView.reloadData()
}
setupLayout()
}
//LAYOUT
fileprivate func setupLayout(){
setNavbar()
}
fileprivate func setNavbar(){
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "icon_arrow_left"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(handleEndButton))
self.navigationController?.navigationBar.barTintColor = UIColor.init(hex: 0xececec)
self.navigationController?.navigationBar.tintColor = UIColor.init(hex: 0x979797)
}
//MAKR:- ACTION
#objc func handleEndButton(){
self.navigationController?.popViewController(animated: true)
}
}
extension GiftCategoryModalVC: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if titleCellData[section].opened == true{
return 2
}else{
return 1
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return titleCellData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: GiftCategoryTBCell.reusableIdentifier, for: indexPath) as! GiftCategoryTBCell
cell.setCategotyNm = categoryTitleModels[indexPath.section].codeNm
if titleCellData[indexPath.section].opened == true{
cell.setImgView = UIImage(named: "arrow_up")
}else{
cell.setImgView = UIImage(named: "arrow_down")
}
return cell
}else{
//this cell is call tableCell
let cell = tableView.dequeueReusableCell(withIdentifier: GiftCategoryListTBCell.reusableIdentifier, for: indexPath) as! GiftCategoryListTBCell
cell.setItems = titleCellData[indexPath.section].sectionData
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0{
if titleCellData[indexPath.section].opened == true{
titleCellData[indexPath.section].opened = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .automatic)
}else{
titleCellData[indexPath.section].opened = true
GiftPageAPIService.shared.selectCode(code: categoryTitleModels[indexPath.section].codeCd!) { (items) in
self.titleCellData[indexPath.section].sectionData = items
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .automatic)
}
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0{
return 50
}else{
let cellHeight: Int = (titleCellData[indexPath.section].sectionData.count + 2) / 3
return self.view.frame.height * 0.24 * CGFloat(cellHeight)
}
}
}
** TableViewCell **
class GiftCategoryListTBCell: UITableViewCell {
#IBOutlet weak var collectionView: UICollectionView!
var items: [ItemModel]?
var category: ItemModel?
var setCategory: ItemModel?{
didSet{
self.category = setCategory!
getCategoryData()
}
}
var setItems: [ItemModel]?{
didSet{
self.items = setItems!
collectionView.reloadData()
}
}
let flowlayout = UICollectionViewFlowLayout()
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: GiftItemCVCell.reusableIdentifier, bundle: nil), forCellWithReuseIdentifier: GiftItemCVCell.reusableIdentifier)
setupLayout()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK:- LAYOUT
fileprivate func setupLayout(){
collectionView.backgroundColor = UIColor.init(hex: 0xf7f7f7)
collectionView.isScrollEnabled = false
}
fileprivate func getCategoryData(){
GiftPageAPIService.shared.selectCode(code: (category?.codeCd)!) { (items) in
self.items = items
self.collectionView.reloadData()
}
}
}
extension GiftCategoryListTBCell: UICollectionViewDataSource,UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if items == nil{
return 0
}else{
return (items?.count)!
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GiftItemCVCell.reusableIdentifier, for: indexPath) as! GiftItemCVCell
cell.setItem = items?[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
/*
I tried to do the work here.
*/
}
}
extension GiftCategoryListTBCell: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: contentView.frame.width * 0.07, left: contentView.frame.width * 0.07, bottom: contentView.frame.width * 0.07, right: contentView.frame.width * 0.07)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return contentView.frame.width * 0.03
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (contentView.frame.width) * 0.25
return CGSize(width: width, height: width * 1.5)
}
}
try this :
let window = UIApplication.shared.keyWindow
window?.topMostWindowController?.navigationController?.popViewController(animated: true)
You mean something like this?
Create a protocol in the tableviewcell file
class myTableCell: UITableViewCell{
var myString = "mystring"
var delegate = myNewDelegate?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.didSelect(text: self.myString)
}
}
protocol myNewDelegate {
func didSelect(text: String)
}
This goes in the view controller class that the table cell is in.
class MyTableViewController: UITableViewController, myNewDelegate{
var stringToPass = String()
func didSelectText(text: String){
stringToPass = text
self.performSegue(withIdentifier: "editProfileSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "editProfileSegue"{
let viewcontroller = segue.destination as! FirstViewController
viewcontroller.myPassedString = self.stringToPass
}
}
}
And then id the receiving class
class FirstViewController: UIViewController{
var myPassedString = String()
}
I understand what your mean.
If you want to pop your controller to previous controller in tablecell just to get its viewcontroller which control the cell and try to pop and if you try this method, why not override delegate func in your viewcontroller ?May a little bit hard to read the code, but useful, and you can use
self.navigationcontroller?.popViewController
If you have already use the viewcontroller to delegate the other tableview, just to judge the tableview name in your delegate func
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == blah blah
{
do what you want
}
}
And if you need to pass the data between the different viewController especially pass the data to pre-viewController you need to write delegate, or need to __block callback.
I make music player using collectionView. I want to when selected collectionView like radio button. If another cell is selected, the selected cell should not be selected. but is not working.
I dont want multi selection. : https://i.stack.imgur.com/ATj3J.png
How do I work? TT I need your help. thx.
this my code.
import UIKit
class PracticeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var homeClassInPrac = HomeViewController()
var songPlayOff = UIImage(named: "play")
var songPlayOn = UIImage(named: "iconStop")
var buttonCounter = [Int]()
var freqNameList = ["Delta 1","Theta 1","Alpha 1","Beta 1","Delta 2","Theta 2","Alpha 2","Beta 2","Delta 3","Theta 3","Alpha 3","Beta 3","Delta 4","Theta 4","Alpha 4","Beta 4"]
#IBOutlet var practiceCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
practiceCollection.delegate = self
practiceCollection.dataSource = self
self.practiceCollection.allowsMultipleSelection = false
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
self.practiceCollection.reloadData()
return freqNameList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:PracticeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "pracCell", for: indexPath) as! PracticeCollectionViewCell
cell.pracImgView.image = songPlayOff
cell.pracLabel.text = freqNameList[indexPath.row]
if buttonCounter.contains(indexPath.row){
cell.pracImgView.image = songPlayOn
}
else{
cell.pracImgView.image = songPlayOff
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if buttonCounter.contains(indexPath.row){
let index = buttonCounter.index(of: indexPath.row)
buttonCounter.remove(at: index!)
self.practiceCollection.reloadData()
homeClassInPrac.audioPlayer2.stop()
}
else{
buttonCounter.removeAll()
buttonCounter.append(indexPath.row)
self.practiceCollection.reloadData()
let buttonInt = buttonCounter[0]
homeClassInPrac.playSound2(freqName: freqNameList[buttonInt])
}
print("Select\(buttonCounter)")
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
print("Deselect\(buttonCounter)")
let index = buttonCounter.index(of: indexPath.row)
buttonCounter.remove(at: index!)
self.practiceCollection.reloadData()
print("Deselect\(buttonCounter)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
I think problem is you are reloading collectionView in numberOfItems method
so Just remove
self.practiceCollection.reloadData()
Change buttonCounter to Array of Bool with equal count to freqNameList
var buttonCounter : Array<Bool> = [false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false]
In cellForItem method use :
if buttonCounter[indexPath.row]{
cell.pracImgView.image = songPlayOn
}
else{
cell.pracImgView.image = songPlayOff
}
In didSelectItem use :
buttonCounter[indexPath.row] = true
homeClassInPrac.playSound2(freqName: freqNameList[buttonInt])
self.practiceCollection.reloadData()
In didDeselectItem use :
buttonCounter[indexPath.row] = false
self.practiceCollection.reloadData()