Setup default row in tableView - ios

I have a problem with setup default row in TableView. I just wanna always pick first element from dataSource. I tried a few solutions with "selectRow" and other but no one of them work.
Here's my code below:
class HomeVC: UIViewController{
#IBOutlet weak var btnSelectCountry: UIButton!
let transparentView = UIView()
let tableView = UITableView()
var selectedButton = UIButton()
var dataSource = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(CellClass.self, forCellReuseIdentifier: "Cell")
let index = NSIndexPath(row: 0, section: 0)
tableView.selectRow(at: index as IndexPath, animated: true, scrollPosition: .bottom)
}
func addTransparentView(frames: CGRect){
let window = UIApplication.shared.keyWindow
transparentView.frame = window?.frame ?? self.view.frame
self.view.addSubview(transparentView)
tableView.frame = CGRect(x: frames.origin.x, y: frames.origin.y + frames.height, width: frames.width, height: 0 )
self.view.addSubview(tableView)
tableView.layer.cornerRadius = 5
transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.9)
tableView.reloadData()
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(removeTransparentView))
transparentView.addGestureRecognizer(tapgesture)
transparentView.alpha = 0
UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveEaseInOut, animations: {
self.transparentView.alpha = 0.5
self.tableView.frame = CGRect(x: frames.origin.x, y: frames.origin.y + frames.height + 5, width: frames.width, height: CGFloat(self.dataSource.count * 50))
}, completion: nil)
}
}
extension HomeVC: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = dataSource[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedButton.setTitle(dataSource[indexPath.row], for: .normal)
removeTransparentView()
}

Try replacing viewDidLoad() with this
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(CellClass.self, forCellReuseIdentifier: "Cell")
let index = IndexPath(row: 0, section: 0)
tableView(tableView, didSelectRowAt: index)
}
This will automatically trigger the didSelectRow method but you need to populate your dataSource before this or the application will crash.
You can try adding this for example in viewWillAppear()
override func viewWillAppear(_ animated: Bool) {
dataSource = ["Your", "Data"]
}

Related

Add UIView and UITableView programmatically

I am trying to make this, as in the first picture:
Image 1
Image 2
But the view somehow does not show up like I want it to. Here you can see my full project code:
import UIKit
import RealmSwift
import CVCalendar
class Test: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myTableView: UITableView = UITableView()
var itemsToLoad: [String] = ["One", "Two", "Three"]
var myView = UIView()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 4/255, green: 4/255, blue: 4/255, alpha: 1.0)
self.navigationController?.navigationBar.barStyle = .black
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.title = "Test"
self.navigationController?.navigationBar.prefersLargeTitles = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Get main screen bounds
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
myView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 150)
myView.backgroundColor = .black
self.view.addSubview(myView)
myTableView.frame = CGRect(x: 0, y: 50, width: screenWidth, height: screenHeight-50);
myTableView.dataSource = self
myTableView.delegate = self
myTableView.backgroundColor = .blue
myTableView.layer.borderWidth = 3
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(myTableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return itemsToLoad.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = self.itemsToLoad[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("User selected table row \(indexPath.row) and item \(itemsToLoad[indexPath.row])")
}
}
Why won't it show up? The first picture is how I want it, then second picture is how it looks now.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if self.itemsToLoad[indexPath.row] != nil {
cell.textLabel?.text = self.itemsToLoad[indexPath.row]
cell.backgroundColor = .white
}else {
cell.backgroundColor = .blue
}
return cell
}

How to acces a view from tableViewCell to TableViewController

I have a UITableViewController and UITableViewCell. Now I am try to access a view from a UITableViewCell to UITableViewController by didSelectRowAt function. But I could not do it.
TableViewController
import Foundation
import UIKit
class FlipViewCon: UIViewController, UITableViewDelegate, UITableViewDataSource{
let flipCellId = "flipCellid"
let flipTableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .green
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
flipTableView.delegate = self
flipTableView.dataSource = self
flipTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(flipTableView)
flipTableView.register(FlipTableViewCell.self, forCellReuseIdentifier: flipCellId)
}
let countryArray = ["bangladesh", "nepal", "china", "malaysia", "thai land", "japan", "England", "canada"]
let cityArray = ["Dhake","Kathmandu", "Beijing", "Kuala Lumpur", "Bangkok", "tokeyo", "London", "Torento"]
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: flipCellId, for: indexPath) as! FlipTableViewCell
//cell.textLabel?.text = countryArray[indexPath.row]
cell.zeroLabel.text = countryArray[indexPath.row]
cell.oneLabel.text = cityArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIView.transition(with: FlipTableViewCell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
FlipTableViewCell.zeroView.isHidden = true
FlipTableViewCell.oneView.isHidden = false
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
UIView.transition(with: FlipTableViewCell.oneView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
FlipTableViewCell.zeroView.isHidden = false
FlipTableViewCell.oneView.isHidden = true
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.flipTableView.frame.width / 4
}
}
TableViewCell
import UIKit
class FlipTableViewCell: UITableViewCell{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static let zeroView = flipView(myColor: .yellow)
static let oneView = flipView(myColor: .green)
static func flipView(myColor: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = myColor
return view
}
let zeroLabel: UILabel = {
let lb = UILabel()
lb.text = "Zero 0"
return lb
}()
let oneLabel: UILabel = {
let lb = UILabel()
lb.text = "one 1"
return lb
}()
func setupView(){
FlipTableViewCell.zeroView.frame = CGRect(x: 0, y: 0, width: frame.width, height:frame.height)
FlipTableViewCell.oneView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
self.addSubview(FlipTableViewCell.zeroView)
self.addSubview(FlipTableViewCell.oneView)
zeroLabel.frame = CGRect(x: 20, y: 0, width: self.frame.width - 40, height: 50)
oneLabel.frame = CGRect(x: 20, y:0, width: self.frame.width - 40, height: 50)
addSubview(zeroLabel)
addSubview(oneLabel)
}
}
Try this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
}
}
Edit
I have update your FlipTableViewCell
it looks like this
class FlipTableViewCell: UITableViewCell{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var zeroView : UIView!
var oneView : UIView!
func flipView(myColor: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = myColor
return view
}
let zeroLabel: UILabel = {
let lb = UILabel()
lb.text = "Zero 0"
return lb
}()
let oneLabel: UILabel = {
let lb = UILabel()
lb.text = "one 1"
return lb
}()
func setupView(){
zeroView = flipView(myColor: .yellow)
oneView = flipView(myColor: .green)
zeroView.frame = CGRect(x: 0, y: 0, width: frame.width, height:frame.height)
oneView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
self.addSubview(zeroView)
self.addSubview(oneView)
zeroLabel.frame = CGRect(x: 20, y: 0, width: self.frame.width - 40, height: 50)
oneLabel.frame = CGRect(x: 20, y:0, width: self.frame.width - 40, height: 50)
addSubview(zeroLabel)
addSubview(oneLabel)
}
}
And Change some code in FlipViewCon
class FlipViewCon: UIViewController, UITableViewDelegate, UITableViewDataSource{
let flipCellId = "flipCellid"
let flipTableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .green
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
flipTableView.delegate = self
flipTableView.dataSource = self
flipTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(flipTableView)
flipTableView.register(FlipTableViewCell.self, forCellReuseIdentifier: flipCellId)
}
let countryArray = ["bangladesh", "nepal", "china", "malaysia", "thai land", "japan", "England", "canada"]
let cityArray = ["Dhake","Kathmandu", "Beijing", "Kuala Lumpur", "Bangkok", "tokeyo", "London", "Torento"]
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: flipCellId, for: indexPath) as! FlipTableViewCell
//cell.textLabel?.text = countryArray[indexPath.row]
cell.zeroLabel.text = countryArray[indexPath.row]
cell.oneLabel.text = cityArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.flipTableView.frame.width / 4
}
}
Edit2
Replace this method in above solution
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
UIView.transition(with: cell.oneView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: nil)
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
}
}
Hope it will work for you
Do like this
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! FlipTableViewCell
// TODO:
}
Just like all the other answers on this post, use the cellForRow(at: IndexPath) method on UITableView, to get a reference to the cells in the table view.
This method returns a UITableViewCell, if the cell is loaded (visible) and nil if the indexPath is not correct or the cell is not loaded.
The code should look like:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
// Do something with cell.
}
TableViewController
import Foundation
import UIKit
class FlipViewCon: UIViewController, UITableViewDelegate, UITableViewDataSource{
let flipCellId = "flipCellid"
let flipTableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .green
tableView.allowsMultipleSelection = true
return tableView
}()
let countryArray = ["India","bangladesh", "nepal", "china", "malaysia", "thai land", "japan", "England", "canada"]
let cityArray = ["Delhi","Dhake","Kathmandu", "Beijing", "Kuala Lumpur", "Bangkok", "tokeyo", "London", "Torento"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
flipTableView.delegate = self
flipTableView.dataSource = self
flipTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(flipTableView)
self.resetFlag()
flipTableView.register(FlipTableViewCell.self, forCellReuseIdentifier: flipCellId)
}
var flagArray : [String] = []
func resetFlag() {
flagArray.removeAll(keepingCapacity: true)
for _ in 0 ..< self.countryArray.count {
self.flagArray.append("0")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: flipCellId, for: indexPath) as! FlipTableViewCell
cell.selectionStyle = .none
if flagArray[indexPath.row] == "0" {
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
}else{
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
}
cell.zeroLabel.text = countryArray[indexPath.row]
cell.oneLabel.text = cityArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
self.flagArray.remove(at: indexPath.row)
self.flagArray.insert("1", at: indexPath.row)
UIView.transition(with: cell.zeroView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: { (complete) in
cell.zeroView.isHidden = true
cell.oneView.isHidden = false
})
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? FlipTableViewCell {
self.flagArray.remove(at: indexPath.row)
self.flagArray.insert("0", at: indexPath.row)
UIView.transition(with: cell.oneView, duration: 0.5, options: .transitionFlipFromLeft, animations: nil, completion: { (complete) in
cell.zeroView.isHidden = false
cell.oneView.isHidden = true
})
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.flipTableView.frame.width / 4
}
}
TableViewCell
import UIKit
class FlipTableViewCell: UITableViewCell{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let zeroView = flipView(myColor: .yellow)
let oneView = flipView(myColor: .green)
static func flipView(myColor: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = myColor
return view
}
let zeroLabel: UILabel = {
let lb = UILabel()
lb.text = "Zero 0"
return lb
}()
let oneLabel: UILabel = {
let lb = UILabel()
lb.text = "one 1"
return lb
}()
func setupView(){
zeroView.frame = CGRect(x: 0, y: 0, width: frame.width, height:frame.width/4)
oneView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.width/4)
self.addSubview(oneView)
self.addSubview(zeroView)
zeroLabel.frame = CGRect(x: 20, y: (frame.width/4)/2 - 25, width: self.frame.width - 40, height: 50)
oneLabel.frame = CGRect(x: 20, y:(frame.width/4)/2 - 25, width: self.frame.width - 40, height: 50)
zeroView.addSubview(zeroLabel)
oneView.addSubview(oneLabel)
}
}

how to select Table View row selection with custom checkbox button?

How to select tableview row with custom button . i have another button called select all its outside of the table view my question is while clicking outside of the tableview button how to select and deselect inside tableview rows? At the same time i could able to select single row in the tableview ? how to do it in swift 3? This is my code in cellforrow method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Custom"
var cell: TStudentAttendanceCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
if cell == nil {
tableView.register(UINib(nibName: "TStudentAttendanceCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
}
print("studentAttendanvceArray--",studentAttendanceArray.object(at: indexPath.row) )
var localDic :NSDictionary!
localDic = studentAttendanceArray.object(at: indexPath.row) as! NSDictionary
Common.sharedInstance.StopActivity()
cell.profile_img.image = self.image
cell.name_lbl.text = localDic["student_name"] as? String
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.contentView.backgroundColor = UIColor.clear
let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 90))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 2.0
whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
whiteRoundedView.layer.shadowOpacity = 0.2
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
return cell
}
ViewController
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var allStudentsArr:[[String:String]] = []
var selectedRows:[IndexPath] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.allowsSelection = false
allStudentsArr = [["name":"name1"],["name":"name2"],["name":"name3"],["name":"name4"],["name":"name5"],["name":"name6"],["name":"name7"],["name":"name8"]]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allStudentsArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomTableViewCell
cell.nameLbl.text = allStudentsArr[indexPath.row]["name"]
if selectedRows.contains(indexPath)
{
cell.checkBox.setImage(UIImage(named:"selected"), for: .normal)
}
else
{
cell.checkBox.setImage(UIImage(named:"unselected"), for: .normal)
}
cell.checkBox.tag = indexPath.row
cell.checkBox.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
return cell
}
#objc func checkBoxSelection(_ sender:UIButton)
{
let selectedIndexPath = IndexPath(row: sender.tag, section: 0)
if self.selectedRows.contains(selectedIndexPath)
{
self.selectedRows.remove(at: self.selectedRows.index(of: selectedIndexPath)!)
}
else
{
self.selectedRows.append(selectedIndexPath)
}
self.tableView.reloadData()
}
#IBAction func selectAllBtnAction(_ sender: UIBarButtonItem) {
self.selectedRows = getAllIndexPaths()
self.tableView.reloadData()
}
func getAllIndexPaths() -> [IndexPath] {
var indexPaths: [IndexPath] = []
for j in 0..<tableView.numberOfRows(inSection: 0) {
indexPaths.append(IndexPath(row: j, section: 0))
}
return indexPaths
}
}
Custom Cell
class CustomTableViewCell: UITableViewCell {
#IBOutlet var nameLbl: UILabel!
#IBOutlet var checkBox: UIButton!
}
Thats how you can programatically select all rows of a single section
#IBAction func didTapSelectAllButton(sender: UIButton) {
let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
for row in 0..<totalRows {
let indexPath = IndexPath(row: row, section: 0)
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
}
If you don't want to use default check box of tableView then disable multipleSelection from tableView and implement logic using an extra global array.
var selectedArrayIndex = [Int]()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedArrayIndex.contains(indexPath.row) {
selectedArrayIndex.remove(at: selectedArrayIndex.index(of: indexPath.row)!)
}else {
selectedArrayIndex.append(indexPath.row)
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if selectedArrayIndex.contains(indexPath.row) {
// Enable You Check
cell.checkBoxView.isHidden = false
}else {
cell.checkBoxView.isHidden = true
}
}
#IBAction func didTapSelectAllButton(sender: UIButton) {
let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
selectedArrayIndex.removeAll()
for row in 0..<totalRows {
selectedArrayIndex.append(row)
}
}

didSelectRowAtIndexPath not working, Swift 3

Can anyone see why in the world didSelectRowAtIndexPath would not be called? I have triple checked by delegate both in the code and in storyboard.
class AddCard: UIViewController,UIPopoverPresentationControllerDelegate, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var cardView: UIView!
#IBOutlet weak var tableView: UITableView!
let tableItems = ["Background Color","Background Image","Font Style","Font Color"]
let cellID = "cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setBackgroundColor (_ color: UIColor) {
cardView.backgroundColor = color
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath as IndexPath)
let row = indexPath.row
cell.textLabel?.text = tableItems[row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
print(indexPath.row)
let row = indexPath.row
switch(row){
case 0:
let popoverVC = storyboard?.instantiateViewController(withIdentifier: "colorPickerVC") as! ColorPickerViewController
popoverVC.modalPresentationStyle = .popover
popoverVC.preferredContentSize = CGSize(width: 284, height: 446)
if let popoverController = popoverVC.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: 0, y: 0, width: 85, height: 30)
popoverController.permittedArrowDirections = .any
popoverController.delegate = self
popoverVC.delegate = self
}
present(popoverVC, animated: true, completion: nil)
break
default: break
}
}
}
Swift 3 modified the signature of the method (a lot of methods too, new "rules"/style)
Replace:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) with
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
Notice the _, the didSelectRowAt vs didSelectRowAtIndexPath, like the other ones you updated (which adapted also the same "style"), but not this one.
Remove the line and let XCode do the autocompletion. Else, you can just replace it with the one from the doc.

TableView background keeps white

I'm having a problem with my parallax effect. I'm having a tableView and a ImageView above the tableView. Now when the user scrolls from the top I want to stretch the image a bit. But the problem is that my tableView keeps having a white background like you can see on the screenshot. So the image isn't visible. The screenshot is taken when the viewcontroller loads and then I just pull down as far as I can go. The tableView has backgroundColor .clear so I don't why it isn't working.
My code:
import UIKit
import PureLayout
class ViewController: UIViewController {
lazy var headerImageView: UIImageView = {
let imageView = UIImageView(forAutoLayout: ())
imageView.image = UIImage(named: "test")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
lazy var tableView: UITableView = {
let tableView = UITableView(forAutoLayout: ())
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.isOpaque = false
tableView.backgroundColor = .clear
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "default")
tableView.tableFooterView = UIView()
tableView.showsVerticalScrollIndicator = false
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.headerImageView)
self.headerImageView.autoPinEdge(toSuperviewEdge: .left)
self.headerImageView.autoPinEdge(toSuperviewEdge: .right)
self.headerImageView.autoPin(toTopLayoutGuideOf: self, withInset: 0)
self.headerImageView.autoSetDimension(.height, toSize: 100)
self.view.addSubview(self.tableView)
self.tableView.autoPinEdge(toSuperviewEdge: .left)
self.tableView.autoPinEdge(toSuperviewEdge: .right)
self.tableView.autoPinEdge(toSuperviewEdge: .bottom)
self.tableView.autoPinEdge(.top, to: .bottom, of: self.headerImageView)
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "default", for: indexPath)
cell.textLabel?.text = "test"
cell.backgroundColor = .red
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Parallax functionality
let yOffset = scrollView.contentOffset.y * 0.2
let availableOffset = min(yOffset, 60)
let contentRectYOffset = availableOffset / self.headerImageView.frame.size.height
self.headerImageView.layer.contentsRect = CGRect(x: 0.0, y: contentRectYOffset, width: 1, height: 1)
}
}

Resources