Swift 2 can not add a slider to a UITableView Cell - ios

I m trying to create a slider cell in a UItableview with swift, it appear, but it's not working, I want to display the value of it in live but it's not working, I tried to use action on the slider itself, I tried changed Editing Changed Method not working too.
Here is my cell code :
import UIKit
class SliderCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var maxLegendLabel: UILabel!
#IBOutlet weak var minLegendLabel: UILabel!
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var answerLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
slider.userInteractionEnabled = true
slider.continuous = true
// slider.addTarget(self, action: #selector(sliderValueChanged), forControlEvents: UIControlEvents.ValueChanged)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func sliderAction(sender: UISlider) {
print("slider ACTION value")
print(sender.value)
}
func sliderValueChanged(sender: UISlider) {
print("slider value")
print(sender.value)
answerLabel.text = "Your choice : " + String(sender.value)
}
func displayBlock(block: Block){
titleLabel.text = block.title
minLegendLabel.text = block.range?.legendMin
maxLegendLabel.text = block.range?.legendMax
slider.minimumValue = Float((block.range?.min)!)!
slider.maximumValue = Float((block.range?.max)!)!
slider.value = 1
}
}
and here is how I declare it in my tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell method :
let cell = tableView.dequeueReusableCellWithIdentifier(CurrentFormTableView.CellIdentifiers.SliderCell, forIndexPath: indexPath) as! SliderCell
cell.displayQuestion(block)
cell.selectionStyle = UITableViewCellSelectionStyle.None
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160.0
return cell

Add this in Table view cell:
sliderDemo = UISlider(frame:CGRectMake(0, 0, 200,20))
var numberOfSteps : NSInteger = numbers.count - 1
sliderDemo.minimumValue = 6.5
sliderDemo.maximumValue = 4.1
sliderDemo.continuous = true
sliderDemo.value = 4.0
sliderDemo.addTarget(self, action: "sliderValueDidChange:", forControlEvents: .ValueChanged)
self.view.addSubview(sliderDemo)
func sliderValueDidChange(sender:UISlider!)
{
println("number:\(sender.value)")
}

I added the slider to the Storyboard itself and in the code I did this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MenuTableViewCell
if indexPath.row == 0 {
cell.slider.alpha = 1
} else {
cell.slider.alpha = 0
}
return cell
}
It means that it will show the slider only on the first cell, and every other cell won't show it.
Of

Related

Custom TableViewCell lose its own variable when scrolling

I have the following Custom TableViewCell
The red(minus) and green(plus) button counts the left label "1"(in code snippet var myQuantity). If I scroll up and down in the tableView the variable myQuantity is always reset to 1 for selected cells.
I read that I have to set the myQuantity in the cellForRowAt method. But how can I set the cell value with its own class variable when its changed via green and red button?
Here my Custom Cell Class:
class ArticleTableViewCell: UITableViewCell {
#IBOutlet var leftLabel: UILabel!
#IBOutlet var rightLabel: UILabel!
#IBOutlet var quantityLabel: UILabel!
var myQuantity = 0
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.quantityLabel.text = String(self.myQuantity)
self.leftLabel.sizeToFit()
self.rightLabel.sizeToFit()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.myQuantity = 1
} else {
self.myQuantity = 0
}
self.quantityLabel.text = String(self.myQuantity)
}
#IBAction func addButton(_ sender: UIButton) {
if !self.isSelected { return }
self.myQuantity += 1
self.quantityLabel.text = String(self.myQuantity)
}
#IBAction func minusButton(_ sender: UIButton) {
if !self.isSelected { return }
if self.myQuantity == 1 { return }
self.myQuantity -= 1
self.quantityLabel.text = String(self.myQuantity)
}}
Here the cellForRowAt Method in my ViewController:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "customArticleCell", for: indexPath) as? ArticleTableViewCell {
let name: String! = categoryArticles[indexPath.row].name
let price = categoryArticles[indexPath.row].price
let price2f = String(format: "%.2f", price)
cell.accessoryType = .none
cell.leftLabel.text = name!
cell.rightLabel.text = "\(price2f) €"
if cell.isSelected {
cell.accessoryType = .checkmark
}
return cell
}
}
class ArticleTableViewCell: UITableViewCell {
#IBOutlet var leftLabel: UILabel!
#IBOutlet var rightLabel: UILabel!
#IBOutlet var quantityLabel: UILabel!
var addAction: (()->())?
var minusAction: (()->())?
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
}
func setupCellWith(data: CategoryArticle) {
self.accessoryType = (data.isSelected == true) ? .checkmark : .none
self.leftLabel.text = data.name
let price2f = String(format: "%.2f", data.price)
self.rightLabel.text = "\(price2f) €"
}
#IBAction func addButton(_ sender: UIButton) {
self.addAction?()
}
#IBAction func minusButton(_ sender: UIButton) {
self.minusAction?()
}
}
struct CategoryArticle {
let name: String
let price: Double
var isSelected: Bool?
var quantity: Int?
}
let categoryArticles: [CategoryArticle] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customArticleCell", for: indexPath) as! ArticleTableViewCell
let categoryArticle = categoryArticles[indexPath.row]
cell.setupCellWith(data: categoryArticle)
cell.minusAction = { [weak self] in
// Action you want to do like decrease the count in the model at indexPath.row and set selection in th model too and reload the tableView cell
}
cell.addAction = { [weak self] in
// Action you want to do like increase the count in the model at indexPath.row and set selection in th model too and reload the tableView cell
}
return cell
}

How i can implement 2 arrays in tableView

`Hello!
I have a tableview and 2 arrays.
When I switch between tabs the tableview reloads. In the first tab, I click on favorites, change the color and add the data to another array. When switching to the second tab, the color does not change. how can i implement this?
MyCell
protocol CellSubclassDelegate: class {
func gestureTapped(cell: StocksCell)
}
class StocksCell: UITableViewCell {
#IBOutlet weak var logoImageView: UIImageView!
#IBOutlet weak var tickerLabel: UILabel!
#IBOutlet weak var favouriteImageView: UIImageView!{ didSet {
let panGesture = UITapGestureRecognizer(target: self, action: #selector(tapToAddFavourite))
favouriteImageView.addGestureRecognizer(panGesture)
favouriteImageView.isUserInteractionEnabled = true
}
}
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var deltaLabel: UILabel!
var selectedCell = false
weak var delegate: CellSubclassDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
#objc private func tapToAddFavourite(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else { return }
if selectedCell{
favouriteImageView.tintColor = UIColor.lightGray
selectedCell = false
}else{
favouriteImageView.tintColor = UIColor.yellow
selectedCell = true
}
self.delegate?.gestureTapped(cell: self)
}
}
MyController
class StocksViewController: UIViewController, CellSubclassDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var stocksLabel: UILabel! { didSet {
let tapGestureStocks = UITapGestureRecognizer(target: self, action: #selector(tapToStocks))
stocksLabel.addGestureRecognizer(tapGestureStocks)
stocksLabel.isUserInteractionEnabled = true
}
}
#IBOutlet weak var favouriteLabel: UILabel!{ didSet {
let tapGestureFavourite = UITapGestureRecognizer(target: self, action: #selector(tapToFavourite))
favouriteLabel.addGestureRecognizer(tapGestureFavourite)
favouriteLabel.isUserInteractionEnabled = true
}
}
fileprivate var stocksData = [StocksModel(n: "VNDX", f: "Vandex, LLC", t: "4 764,6 ₽", tt: "+55 ₽ (1,15%)"), StocksModel(n: "DDD", f: "Dandex, LLC", t: "1 764,6 ₽", tt: "+155 ₽ (1,15%)")]
var favouriteData = [StocksModel]()
let privateIdentifire = "StocksCell"
var isStocksSelected = true
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
#objc private func tapToFavourite(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else { return }
favouriteLabel.alpha = 1
favouriteLabel.font = favouriteLabel.font.withSize(28)
stocksLabel.alpha = 0.65
stocksLabel.font = stocksLabel.font.withSize(18)
stocksLabel.textAlignment = .center
isStocksSelected = false
tableView.reloadData()
}
#objc private func tapToStocks(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else { return }
favouriteLabel.alpha = 0.65
favouriteLabel.font = favouriteLabel.font.withSize(18)
stocksLabel.alpha = 1
stocksLabel.font = stocksLabel.font.withSize(28)
stocksLabel.textAlignment = .left
isStocksSelected = true
tableView.reloadData()
}
}
TABLEVIEW DATASOURCE
extension StocksViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let result = isStocksSelected ? stocksData.count : favouriteData.count
return result
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: privateIdentifire, for: indexPath) as! StocksCell
cell.delegate = self
if isStocksSelected{
cell.tickerLabel.text = stocksData[indexPath.row].name
cell.companyNameLabel.text = stocksData[indexPath.row].fullname
cell.priceLabel.text = stocksData[indexPath.row].ticker
cell.deltaLabel.text = stocksData[indexPath.row].tq
}else{
cell.tickerLabel.text = favouriteData[indexPath.row].name
cell.companyNameLabel.text = favouriteData[indexPath.row].fullname
cell.priceLabel.text = favouriteData[indexPath.row].ticker
cell.deltaLabel.text = favouriteData[indexPath.row].tq
}
return cell
}
func gestureTapped(cell: StocksCell) {
guard let indexPath = self.tableView.indexPath(for: cell) else {return}
if cell.selectedCell{
let dataStock = stocksData[indexPath.row]
favouriteData.append(dataStock)
}else{
favouriteData.remove(at: indexPath.row)
}
}
}
TABLEVIEW DELEGATE
extension StocksViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 68
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.layer.cornerRadius = 16
}
}
Change the color here:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: privateIdentifire, for: indexPath) as! StocksCell
cell.delegate = self
if isStocksSelected{
favouriteImageView.tintColor = UIColor.lightGray
cell.tickerLabel.text = stocksData[indexPath.row].name
cell.companyNameLabel.text = stocksData[indexPath.row].fullname
cell.priceLabel.text = stocksData[indexPath.row].ticker
cell.deltaLabel.text = stocksData[indexPath.row].tq
}else{
favouriteImageView.tintColor = UIColor.yellow
cell.tickerLabel.text = favouriteData[indexPath.row].name
cell.companyNameLabel.text = favouriteData[indexPath.row].fullname
cell.priceLabel.text = favouriteData[indexPath.row].ticker
cell.deltaLabel.text = favouriteData[indexPath.row].tq
}
return cell
}

UISwitch state in Tableviewcell resets when user scrolls - Swift

I've searched for a solutions on this issue but none seem to work for my use case.
I have a table inside a viewcontroller and the issue I am facing is that when scrolling the UISwitch state is reset to OFF. I understand table cells are reused, but how do I implement a solution that will restore the state of UISwitch when a user scrolls based on my code below
import UIKit
class StirrViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var mylabel: UILabel!
var myString = String()
#IBAction func stirrBtn(_ sender: AnyObject) {
}
var timeSelected = String()
var selectedTimeArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
mylabel.text = myString
self.timeSelected = myString
}
func switchChanged(_ sender : UISwitch!){
print("table row switch Changed \(sender.tag)")
print("The switch is \(sender.isOn ? "ON" : "OFF")")
let kValue = (sender.tag + 1)
let keyValue = String(kValue)
if sender.isOn {
recipeSettings.boolStirrSwitch[keyValue] = true
recipeSettings.switchedOnArr.append(keyValue)
} else {
recipeSettings.boolStirrSwitch[keyValue] = false
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let stringNum = Int(self.timeSelected)
recipeSettings.recipeTimeSet2 = stringNum!
return(stringNum)!
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UITableViewCell
//here is programatically switch make to the table view
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell.accessoryView = switchView
// Process data displayed in rows(minutes)
let endTime = Int(self.timeSelected)
let startTime = Int(1)
// Recipe time array
let timeArray: [Int] = Array(startTime...endTime!)
let stringTimeArr = timeArray.map{String($0)}
// Save time array to global variable
recipeSettings.recipeTimeSetArr = stringTimeArr
// Create a boolean Array to hold all default false booleans
let defBool: Bool = false
var defBoolArr: [Bool] = []
// Fill the array with the defaults boolean
for _ in 0..<stringTimeArr.count{defBoolArr.append(defBool)}
// Map the array to global dictionary containing the Time in an array and default "false" value
for i in 0..<stringTimeArr.count {
recipeSettings.boolStirrSwitch[stringTimeArr[i]] = defBoolArr[i]
}
// Add the minutes to cell table
cell.textLabel?.text = stringTimeArr[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
As you can see in my code I do save the state of each UI switch in a global variable dictionary. How can I solve the issue of UISwitch changing states based on this code? All help is appreciated. Thanks in advance
var switchState = [String : Bool]()
your recipeSettings.boolStirrSwitch should be decleard like that.
As you are using timeSelected as numberOfRowsInSection as showing
your cell.textLabel from that so you don't need extra stringTimeArr
for that.
All the processing you do in cellForRowAt it will happen again and
again table cells are reused so for setting up data do it in another
function then reload TableView.
Solution for your problem should be look like that.
import UIKit
class StirrViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
//make tableView IBOutlet for reloading data
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var mylabel: UILabel!
var myString = String()
#IBAction func stirrBtn(_ sender: AnyObject) {
}
var timeSelected = String()
var selectedTimeArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
mylabel.text = myString
self.timeSelected = myString
self.setdefaultSwitchState()
}
//recipeSettings.boolStirrSwitch should be decleard like that
var switchState = [String : Bool]()
//setDeaultSwitchState
func setdefaultSwitchState(){
if let timeSelected = Int(self.timeSelected){
for value in 0..<timeSelected{
switchState["\(value)"] = false
//or
//recipeSettings.boolStirrSwitch["\(value)"] = false
}
}
self.tableView.reloadData()
}
#objc func switchChanged(_ sender : UISwitch!){
print("table row switch Changed \(sender.tag)")
print("The switch is \(sender.isOn ? "ON" : "OFF")")
let kValue = (sender.tag + 1)
let keyValue = String(kValue)
if sender.isOn {
switchState[keyValue] = true
} else {
switchState[keyValue] = false
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let stringNum = Int(self.timeSelected)
recipeSettings.recipeTimeSet2 = stringNum!
return(stringNum)!
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UITableViewCell
//here is programatically switch make to the table view
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell.accessoryView = switchView
cell.textLabel?.text = "\(indexPath.row + 1)"
if let switchState = switchState["\(indexPath.row)"] {
if switchState{
switchView.isOn = true
}else{
switchView.isOn = false
}
}else{
switchView.isOn = false
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Stepper on tableview cell (swift)

I put stepper both outlets and action into tableview cell and using protocol delegate to connect it to tableview. When i tapped stepper in first row, stepper value appear normaly in first row but its also appear in some random row. how to fix this?
TableViewCell
protocol ReviewCellDelegate{
func stepperButton(sender: ReviewTableViewCell)
}
class ReviewTableViewCell: UITableViewCell {
#IBOutlet weak var countStepper: UIStepper!
#IBOutlet weak var stepperLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func stepperButtonTapped(sender: UIStepper) {
if delegate != nil {
delegate?.stepperButton(self)
stepperLabel.text = "x \(Int(countStepper.value))"
}
}
ViewController
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "reviewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell
var imageView: UIImageView?
let photoG = self.photos[indexPath.row]
imageView = cell.contentView.viewWithTag(1) as? UIImageView
//let layout = cell.goodiesImage
let tag = indexPath.row // +1
cell.tag = tag
photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in
if cell.tag == tag {
imageView?.image = image
cell.goodiesImage.image = image
}
})
func stepperButton(sender: ReviewTableViewCell) {
if let indexPath = tableView.indexPathForCell(sender){
print(indexPath)
}
}
Reset the value of stepper while loading your cell. you can reset the cell property values in cell's prepareForReuse method. add the following method in your ReviewTableViewCell class.
override func prepareForReuse()
{
super.prepareForReuse()
countStepper.value = 0.0
}
In tableViewCell VC:
1 - add these field
var cellDelegate: cellProtocol?
var index: IndexPath?
2 - then add this in the delegate:
func onStepperClick(index: Int, sender: UIStepper)
3 - when you have dragged your stepper over as an action use this:
#IBAction func cellStepper(_ sender: UIStepper) {
cellDelegate?.onStepperClick(index: (index?.row)!, sender: sender)
sender.maximumValue = 1 //for incrementing
sender.minimumValue = -1 //for decrementing
//this will make sense later
}
In ViewController
1 - add these to the tableView function that has the cellAtRow variable.
cell.cellDelegate = self
cell.index = indexPath
2 - Use this instead of your stepperButton function
func onStepperClick(index: Int, sender: UIStepper) {
print(index)
if sender.value == 1.0{
//positive side of stepper was pressed
}else if sender.value == -1.0{
//negative side of stepper was pressed
}
sender.value = 0 //resetting to zero so sender.value produce different values on plus and minus
}
Hope this works for you
As mentioned by #A-Live, your component is being reused and so need to be updated.
So in your view controller:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "reviewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell
var imageView: UIImageView?
let photoG = self.photos[indexPath.row]
imageView = cell.contentView.viewWithTag(1) as? UIImageView
//let layout = cell.goodiesImage
let tag = indexPath.row // +1
cell.tag = tag
photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in
if cell.tag == tag {
imageView?.image = image
cell.goodiesImage.image = image
}
})
cell.countStepper.value = XXX[indexPath.row].value; //Here you update your view
cell.stepperLabel.text = "x \(Int(cell.countStepper.value))" //And here
And
func stepperButton(sender: ReviewTableViewCell) {
if let indexPath = tableView.indexPathForCell(sender){
print(indexPath)
XXX[sender.tag].value = sender.counterStepper.value //Here you save your updated value
}
NOTE:
1.MY Cell class is just normal..All changes are in viewcontroller class
2.I have taken stepper and over it added ibAddButton with same constraint as ibStepper
class cell: UITableViewCell {
#IBOutlet weak var ibAddButton: UIButton!
#IBOutlet weak var ibStepper: UIStepper!
#IBOutlet weak var ibCount: UILabel!
#IBOutlet weak var ibLbl: UILabel!
}
1.define empty int array [Int]()
var countArray = [Int]()
2.append countArray with all zeros with the number of data u want to populate in tableview
for arr in self.responseArray{
self.countArray.append(0)
}
3.in cell for row at
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cell
let dict = responseArray[indexPath.row] as? NSDictionary ?? NSDictionary()
cell.ibLbl.text = dict["name"] as? String ?? String()
if countArray[indexPath.row] == 0{
cell.ibAddButton.tag = indexPath.row
cell.ibStepper.isHidden = true
cell.ibAddButton.isHidden = false
cell.ibCount.isHidden = true
cell.ibAddButton.addTarget(self, action: #selector(addPressed(sender:)), for: .touchUpInside)
}else{
cell.ibAddButton.isHidden = true
cell.ibStepper.isHidden = false
cell.ibStepper.tag = indexPath.row
cell.ibCount.isHidden = false
cell.ibCount.text = "\(countArray[indexPath.row])"
cell.ibStepper.addTarget(self, action: #selector(stepperValueChanged(sender:)), for: .valueChanged)}
return cell
}
4.objc functions
#objc func stepperValueChanged(sender : UIStepper){
if sender.stepValue != 0{
countArray[sender.tag] = Int(sender.value)
}
ibTableView.reloadData()
}
#objc func addPressed(sender : UIButton){
countArray[sender.tag] = 1//countArray[sender.tag] + 1
ibTableView.reloadData()
}

How to alter a button in cell on click in swift ios?

I have a table layout inside a view which as a custom cell,The problem I'm facing is that the cells inside has a button i want to hide the button in cell on clicking it(only the one that is clicked should be hidden) how can i do thing in correct method?
ScrollCell.swift
class ScrollCell: UITableViewCell {
#IBOutlet weak var ProfilePic: SpringImageView!
#IBOutlet weak var UserName: SpringButton!
#IBOutlet weak var Closet: UILabel!
#IBOutlet weak var Style: UILabel!
//------//
#IBOutlet weak var MianImg: UIImageView!
//-------//
#IBOutlet weak var ProductName: UILabel!
#IBOutlet weak var LoveCount: UIButton!
#IBOutlet weak var Discount: UILabel!
#IBOutlet weak var OrginalPrice: UILabel!
#IBOutlet weak var Unliked: UIButton!
#IBOutlet weak var Liked: UIButton!
#IBOutlet weak var Comment: UIButton!
#IBOutlet weak var Share: SpringButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
ProfilePic.layer.cornerRadius = ProfilePic.bounds.height / 2
ProfilePic.clipsToBounds = true
}
}
ScrollController.swift
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 // however many sections you need
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(try! Realm().objects(Feed))
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
return tan.count // however many rows you need
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// get an instance of your cell
cell = tableView.dequeueReusableCellWithIdentifier("ScrollCellDqueue", forIndexPath: indexPath) as! ScrollCell
IndexPath = indexPath.row
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
cell.ProfilePic.kf_setImageWithURL(NSURL(string:tan[indexPath.row].ProfilePic)!)
cell.UserName.setTitle(tan[indexPath.row].FullName, forState: .Normal)
cell.Style.text = tan[indexPath.row].StyleType
if tan[indexPath.row].UserType == "store_front"{
cell.Closet.text = "Store Front"
}else if tan[indexPath.row].UserType == "normal"{
cell.Closet.text = "Pri Loved"
}
//-----//
var SingleImage:String = ""
var ImageArray = tan[indexPath.row].ImageArraySet.componentsSeparatedByString(",")
SingleImage = ImageArray[0]
cell.MianImg.kf_setImageWithURL(NSURL(string:SingleImage)!)
//-----//
cell.ProductName.text = tan[indexPath.row].ItemName
cell.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
cell.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
cell.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
if(tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = true
cell.Liked.hidden = false
}
else if (!tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = false
cell.Liked.hidden = true
}
cell.Unliked.tag = tan[indexPath.row].ID
cell.Liked.tag = tan[indexPath.row].ID
return cell
}
#IBAction func LikeBtn(sender: AnyObject) {
print(sender.tag)
print(IndexPath)
//here i want to know who i can hide the button i have clicked ?
}
Here i want to access the cell in which button is clicked and make changes to UI item inside that cell how can i do that ?
There are many ways to do it. One possible solution is use block.
Add this to ScrollCell
var didLikedTapped: (() -> Void)?
and receive the event of the LikedButton in the cell
#IBAction func LikeBtn(sender: AnyObject) {
didLikedTapped?()
}
Then in cellForRowAtIndexPath of viewController add this
cell.didLikedTapped = {[weak self] in
print(IndexPath)
}
Liked is uibutton in ScrollCell, i don't known, why can you add IBAction for it in ScrollController? . You must implement it in ScrollCell And code:
#IBAction func LikeBtn(sender: UIButton) {
print(sender.tag)
sender.hiden = true
}
And i think, if you have only one UIbutton, it will better. In there, like and unlike is 2 state of uibutton(seleted and none). When you click the button, change it's state
Update:
class sampleCell: UITableViewCell{
#IBOutlet var btnLike : UIButton!
#IBOutlet var btnUnLike : UIButton! // frame of 2 button is equal
override func awakeFromNib() {
super.awakeFromNib()
self.btnUnLike.hidden = true
// ...
}
func updateData(data:AnyObject){ // data's type is Feed
// set data for cell
// i think you should implement in here. and in ScollController call : cell.updateData() , it's better
/* e.x
self.ProductName.text = tan[indexPath.row].ItemName
self.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
self.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
self.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
*/
}
#IBAction func likeTap(sender:UIButton){ // rememeber set outlet event for btnLike and btnUnLike is this function
if sender == self.btnLike{
self.btnLike.hidden = true
self.btnUnLike.hidden = false
// do s.t
}else if sender == self.btnUnLike{
self.btnLike.hidden = false
self.btnUnLike.hidden = true
// do s.t
}
}
}
Check if the following code help
#IBAction func LikeBtn(sender: AnyObject) {
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(position)
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
UITableViewCell
print(indexPath?.row)
}
give the LikeBtn the property indexpath, in cellForRowAtIndexPath method, pass the indexPath to the LikeBtn, then you will know which cell's LikeBtn clicked.
class LikeBtn: UIButton {
var indexPath: NSIndexPath?
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// here pass the indexpath to your button
cell.likeBtn.indexPath = indexPath
return cell
}
#IBAction func likeTap(sender: LikeBtn){
if let indexPath = sender.indexPath {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
//here you will know the exact cell, now you can hide or show your buttons
}
}
}

Resources