How to get tableview data with multi button selection swift? - ios

I want to get data from tableview after clicking save button .But when user second time change the value then, same value two times append .[
[enter image description here][1]
][2]
protocol ButtonSelect {
func tapStar(indexPath: IndexPath, star: Int)
}
class LeaveDayDetailsCell: UITableViewCell {
#IBOutlet weak var leaveDateLabel: UILabel!
#IBOutlet weak var leaveDateName: UILabel!
#IBOutlet weak var firstButton: UIButton!
#IBOutlet weak var seconButton: UIButton!
#IBOutlet weak var fullButton: UIButton!
var delegate:ButtonSelect?
var indexpath:IndexPath?
#IBAction func bittonPressed(_ sender: UIButton) {
delegate?.tapStar(indexPath: indexpath!, star: sender.tag)
}
}
class DayDetailsController: UIViewController{
#IBAction func buttonPresed(_ sender: UIButton) {
// i want to submit tableview result with radio button value change this place
// example like
//["03/27/2021 + 1", "03/28/2021 + 2"]
// my result
//["03/27/2021 + 1", "03/28/2021 + 2", "03/27/2021 + 3", "03/28/2021 + 2"]
// same value two times
}
}
extension DayDetailsController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listDayDetailsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"LeaveDayDetailsCell",for: indexPath) as! LeaveDayDetailsCell
cell.leaveDateLabel.text = listDayDetailsData[indexPath.row]["BreakDate"] as? String ?? "-"
cell.leaveDateName.text = listDayDetailsData[indexPath.row]["DateName"] as? String ?? "-"
cell.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
cell.layer.borderWidth = 2
dayDetailsTableView.rowHeight = 132.00
cell.delegate = self
cell.indexpath = indexPath
return cell
}
}
extension DayDetailsController:ButtonSelect{
func tapStar(indexPath: IndexPath, star: Int) {
let cell = dayDetailsTableView.cellForRow(at: indexPath) as! LeaveDayDetailsCell
if star == 1{
cell.firstButton.setImage(UIImage(named: "radioFull.png"), for: .normal)
cell.seconButton.setImage(UIImage(named: "radioBlank.png"), for: .normal)
cell.fullButton.setImage(UIImage(named: "radioBlank.png"), for: .normal)
totalvalue = star
}
else if star == 2{
cell.firstButton.setImage(UIImage(named: "radioBlank.png"), for: .normal)
cell.seconButton.setImage(UIImage(named: "radioFull.png"), for: .normal)
cell.fullButton.setImage(UIImage(named: "radioBlank.png"), for: .normal)
totalvalue = star
}
else if star == 3{
cell.firstButton.setImage(UIImage(named: "radioBlank.png"), for: .normal)
cell.seconButton.setImage(UIImage(named: "radioBlank.png"), for: .normal)
cell.fullButton.setImage(UIImage(named: "radioFull.png"), for: .normal)
totalvalue = star
}
answerValue.append("\(listDayDetailsData[indexPath.row]["BreakDate"] as! String) + \(totalvalue)")
print(answerValue,"****answer")
}
}

Keep the star count in your listDayDetailsData and update the value according to the button taps
LeaveDayDetailsCell
class LeaveDayDetailsCell: UITableViewCell {
#IBOutlet weak var leaveDateLabel: UILabel!
#IBOutlet weak var leaveDateName: UILabel!
#IBOutlet weak var firstButton: UIButton!
#IBOutlet weak var seconButton: UIButton!
#IBOutlet weak var fullButton: UIButton!
}
DayDetailsController extension
extension DayDetailsController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listDayDetailsData.count
}
#objc func firstButtonPressed(sender: UIButton) {
let index = sender.tag
// Update star value in listDayDetailsData[index]
// Reload single row at index 0
dayDetailsTableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
}
#objc func secondButtonPressed(sender: UIButton) {
let index = sender.tag
// Update star value in listDayDetailsData[index]
// Reload single row at index 0
dayDetailsTableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
}
#objc func fullButtonPressed(sender: UIButton) {
let index = sender.tag
// Update star value in listDayDetailsData[index]
// Reload single row at index 0
dayDetailsTableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"LeaveDayDetailsCell",for: indexPath) as! LeaveDayDetailsCell
// cell.leaveDateLabel.text = listDayDetailsData[indexPath.row]["BreakDate"] as? String ?? "-"
// cell.leaveDateName.text = listDayDetailsData[indexPath.row]["DateName"] as? String ?? "-"
cell.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
cell.layer.borderWidth = 2
cell.firstButton.tag = indexPath.row
cell.seconButton.tag = indexPath.row
cell.fullButton.tag = indexPath.row
cell.firstButton.addTarget(self, action: #selector(firstButtonPressed(sender:)), for: .touchUpInside)
cell.firstButton.addTarget(self, action: #selector(secondButtonPressed(sender:)), for: .touchUpInside)
cell.firstButton.addTarget(self, action: #selector(fullButtonPressed(sender:)), for: .touchUpInside)
switch listDayDetailsData[indexPath.row]["Star"] as! Int {
case 1:
// Update your cell buttons
break
case 2:
// Update your cell buttons
break
case 3:
// Update your cell buttons
break
default:
// Default case
break
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 132.00
}
}
Pro tip:
It's better to use an Object for keeping your data than a Dictionary
eg
struct DayDetails {
var breakDate: String
var dateName: String
var stars: Int
//....
}
And there are third party libraries available for handling star rating UI as well
https://github.com/evgenyneu/Cosmos

Related

plus or minus button values is not updated in swift

I working on cart view controller I tried some of code, it's show like below image.
values updating every row in tableview, if I click on product1 plusbutton count is increase showing 1 .when I click on product2 plusbutton value is showing 2.count is increasing.minus every time minusbutton also working same like that.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
cell.minusButton.tag = indexPath.row
cell.plusbutton.tag = indexPath.row
cell.minusButton.addTarget(self, action: #selector(minusbuttonClick), for: .touchUpInside)
cell.plusbutton.addTarget(self, action: #selector(plusButtonClick), for: .touchUpInside)
return cell
}
#objc func minusbuttonClick(sender : UIButton)
{
let cell = Tableview.cellForRow(at: NSIndexPath(row: sender.tag, section: 0) as IndexPath) as! CustomTableViewCell
if(count > 0){
count -= 1
}
let myString = String(count)
cell.countLabel.text = myString
if count == 0{
cell.countLabel.text = ""
}
self.Tableview.reloadData()
}
#objc func plusButtonClick(sender : UIButton)
{
let cell = Tableview.cellForRow(at: NSIndexPath(row: sender.tag, section: 0) as IndexPath) as! CustomTableViewCell
count += 1
let myString = String(count)
cell.countLabel.text = myString
self.Tableview.reloadData()
}
I have to show when I click product1 value should be 1, if I click on product2 value as 1
minus also decrease same like that
first thing to do is create a struct to hold your data
struct ProductData {
var count : Int
var name : String
}
and you can use that in your ViewController
var productData : [ProductData] = []
the, of course, you need to add some data - here's a simple set to get started
override func viewDidLoad() {
super.viewDidLoad()
// set up some data.
productData.append(ProductData(count: 0, name: "product 1"))
productData.append(ProductData(count: 0, name: "product 2"))
productData.append(ProductData(count: 0, name: "product 3"))
productData.append(ProductData(count: 0, name: "product 4"))
}
using the delegate model described earlier swift: how to get the indexpath.row when a button in a cell is tapped? update your custom table view cell
protocol TableViewCellCustomDelegate: class {
func buttonTapped(index : Int, delta : Int)
}
class TableViewCellCustom: UITableViewCell {
weak var delegate: TableViewCellCustomDelegate?
#IBOutlet weak var minusButton: UIButton!
#IBOutlet weak var plusButton: UIButton!
#IBOutlet weak var countLabel: UILabel!
#IBOutlet weak var productLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
self.delegate = nil
}
#IBAction func minusButtonClick(_ sender: UIButton) {
delegate?.buttonTapped(index: sender.tag, delta : -1)
}
#IBAction func plusButtonClick(_ sender: UIButton) {
delegate?.buttonTapped(index: sender.tag,delta : +1)
}
}
update the delegate methods in your view controller. I've done it here with a single method to add or delete, but you could split it out if you want to do other things as well.
extension ViewController: TableViewCellCustomDelegate {
func buttonTapped(index: Int, delta : Int)
{
productData[index].count += delta
if productData[index].count < 0
{
productData[index].count = 0
}
tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
}
and update your cellForRowAt definition
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! TableViewCellCustom
cell.countLabel.text = "\(productData[indexPath.row].count)"
cell.productLabel.text = productData[indexPath.row].name
cell.minusButton.tag = indexPath.row
cell.plusButton.tag = indexPath.row
cell.delegate = self
return cell
}

How to increment and decrement value of label in tableview and make total price from label value in swift?

now cell value are dynamically and its look after calling api.
I want to make total of all tickets price at last. I refer this link How do I increment/decrement a label value with two buttons pressed in tableview Swift and make changes in my code but didn't work for me.
struct Product {
var price = 0
}
class TicketBookingVC: UIViewController , UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblView: UITableView!
#IBOutlet weak var mainTblView: UIView!
var bookingDetails = NSDictionary()
var productArray = [Product]()
var product : Product!
private var counterValue = 1
var productIndex = 0
var counterLbl = UILabel()
#IBOutlet weak var bookBtn: UIButton!
#IBOutlet weak var eventImg: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tblView.delegate = self
tblView.dataSource = self
for _ in 0...10{
productArray.append(Product(price: 1))
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
else if section == 1{
return 4
}
else{
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellfirst", for: indexPath)
cell.selectionStyle = .none
return cell
}
else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellsecond", for: indexPath)
let mainViewCell = cell.contentView.viewWithTag(2000) as! UIView
let normalView = cell.contentView.viewWithTag(2001) as! UIView
let eventName = cell.contentView.viewWithTag(2003) as! UILabel
let eventPrice = cell.contentView.viewWithTag(2004) as! UILabel
counterLbl = cell.contentView.viewWithTag(2007) as! UILabel
let decrementBtn = cell.contentView.viewWithTag(2005) as! UIButton
let incrementBtn = cell.contentView.viewWithTag(2006) as! UIButton
decrementBtn.addTarget(self, action:#selector(self.decrementbuttonClicked), for: .touchUpInside)
incrementBtn.addTarget(self, action:#selector(self.incrementbuttonClicked), for: .touchUpInside)
product = productArray[indexPath.row]
counterLbl.text = "\(product.price)"
cell.selectionStyle = .none
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellthird", for: indexPath)
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0{
return UITableView.automaticDimension
}
else{
return 80
//return UITableView.automaticDimension
}
}
#objc func decrementbuttonClicked() {
print("Button decrement")
if(counterValue != 1){
counterValue -= 1;
}
self.counterLbl.text = "\(counterValue)"
product.price = counterValue
}
#objc func incrementbuttonClicked() {
counterValue += 1;
self.counterLbl.text = "\(counterValue)"
product.price = counterValue
}
func addProductToCart(product: Product, atindex: Int) {
productArray[atindex] = product
calculateTotal()
}
func calculateTotal()
{
var totalValue = 0
for objProduct in productArray {
totalValue += objProduct.price
}
self.eventPrice.text = "Total \(totalValue)"
}
}
when I increment or decrement value of first cell it reflect in 4th cell. please help. I am new at swift.
This is due to cell reuse. You should set a model for each cell

radio buttons in a tableview cells swift

Currently I am trying to make a store-like view that shows multiple different listing (spaceships) and you can only select one at a time. It would be for a game where you can select your different spaceships. I am sing a UITableView with a UITableViewCell Xib file. I have only one table cell Xib file to format all of the different listings. The style of the Select button is suppose to be like a Radio Button.
The difficulty I am having is that when I click one button, it makes all the buttons say "Selected."
This is the code that I have:
TableViewController:
import UIKit
struct CellData {
var image: UIImage?
var message: String?
var id: Int?
}
var array = [String]()
var buttonArray = [ShopButton]()
class ViewController: UITableViewController {
var data = [CellData]()
override func viewDidLoad() {
super.viewDidLoad()
data = [CellData.init(image: #imageLiteral(resourceName: "ship_0"), message: "Red Ship", id: 0), CellData.init(image: #imageLiteral(resourceName: "ship_1"), message: "Blue Ship", id: 1), CellData.init(image: #imageLiteral(resourceName: "ship_3"), message: "Yellow Ship", id: 2)]
array = ["Select", "Select", "Select"]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
cell.mainImageView.image = data[indexPath.row].image
cell.mainLabel.text = data[indexPath.row].message
cell.buttonOutlet.setTitle(array[indexPath.row], for: .normal)
cell.buttonOutlet.tag = data[indexPath.row].id!
buttonArray.append(cell.buttonOutlet)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
}
TableViewCell
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var mainImageView: UIImageView!
#IBOutlet weak var mainLabel: UILabel!
#IBOutlet weak var buttonOutlet: ShopButton!
#IBAction func button(_ sender: ShopButton) {
buttonOutlet.makeSelected()
}
override func awakeFromNib() {
super.awakeFromNib()
}
My SubClass for the UIButton:
import UIKit
class ShopButton: UIButton {
var buttonID = Int()
func makeSelected() {
switch self.buttonID {
case 0:
array = ["Selected", "Select", "Select"]
buttonTitle()
print("Ship: Red Ship")
case 1:
array = ["Select", "Selected", "Select"]
buttonTitle()
print("Ship: Blue Ship")
case 2:
array = ["Select", "Select", "Selected"]
buttonTitle()
print("Ship: Yellow Ship")
default:
print("Error: Default Initiated")
}
}
func buttonTitle() {
for button:ShopButton in buttonArray {
button.setTitle(array[button.buttonID], for: .normal)
}
}
override func awakeFromNib() {
}
}
I realize this might not be the best approach to making this shop setup so if anyone has an answer to how to fix this or a different way that would be much better than what I have currently done, it would be much appreciated. Thanks.
You can possibly use this logic in didSelectRowAt in table view like:
You can make the tag of button equivalent to the indexpath.row of tableview
for (button in buttons) {
button.isSelected = false;
}
if button.tag == indexpath.row{ //Here sender.tag would be your indexPath.row
button.isSelected = true;
button.setImage(#imageLiteral(resourceName: "ic_Radio_filled"), for: .normal)
}else{
button.isSelected = false;
button.setImage(#imageLiteral(resourceName: "ic_Radio_Empty"), for: .normal)
}
Let me know if it works for you.

Problems updating UITableView cell and SwiftyPickerPopover

The problem is that when I am selecting some value (in the field picker -SwiftyPickerPopover-) in a row, the action updates the same value (selected in picker) for all rows.
The code that I am using for this for the ViewController (with UITableView inside):
func btnExpenseTypePressed(at index: IndexPath) {
var tiposGasto: [String] = [String]()
for gasto in dataManager.expensesType {
tiposGasto.append(gasto.tipoGasto!)
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: index) as! ExpenseDetailCell
StringPickerPopover.appearFrom(
originView: cell.btnExpenseType,
baseViewController: self,
title: "Tipos de Gasto",
choices: tiposGasto,
initialRow:0,
doneAction: { selectedRow, selectedString in
print("Seleccion \(selectedString)")
//self.valueSelected = selectedString
cell.btnExpenseType.setTitle(selectedString, for: .normal)
self.tableView.reloadData()
} ,cancelAction: { print("cancel")}
)
}
func btnCostCenterPressed(at index: IndexPath) {
var centroCoste: [String] = [String]()
for centro in dataManager.costsCenter {
centroCoste.append(centro.centroCoste!)
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: index) as! ExpenseDetailCell
StringPickerPopover.appearFrom(
originView: cell.btnCostCenter,
baseViewController: self,
title: "Centro de Coste",
choices: centroCoste,
initialRow:0,
doneAction: { selectedRow, selectedString in
print("Seleccion \(selectedString)")
//self.valueSelected = selectedString
cell.btnCostCenter.setTitle(selectedString, for: .normal)
self.tableView.reloadData()
} ,cancelAction: { print("cancel")}
)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell? = UITableViewCell()
if tableView == self.tableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! ExpenseDetailCell
cell.selectionStyle = .none
cell.delegate = self
debugPrint("First table load \(firstTableLoad)")
if firstTableLoad {
cell.btnCostCenter.setTitle(dataManager.costsCenter[0].centroCoste, for: .normal)
cell.btnExpenseType.setTitle(dataManager.expensesType[0].tipoGasto, for: .normal)
firstTableLoad = false
}
return cell
}
if tableView == self.tableViewImages {
let cell = tableView.dequeueReusableCell(withIdentifier: "imagesCellIdentifier", for: indexPath) as! ExpenseImageCell
cell.imageView?.image = UIImage(named: "imgPlaceholder")
cell.selectionStyle = .none
return cell
}
return cell!
}
The btnExpenseTypePressed and btnCostCenterPressed methods are delegate from the ExpenseDetailCell:
protocol ExpenseDetailDelegate {
func switchChanged(at index: IndexPath)
func amountEditedChanged(at index: IndexPath)
func btnExpenseTypePressed(at index: IndexPath)
func btnCostCenterPressed(at index: IndexPath)
}
class ExpenseDetailCell: UITableViewCell {
var delegate: ExpenseDetailDelegate!
var indexPath: IndexPath!
var dataManager = DataManager.sharedInstance
#IBOutlet weak var txtAmountNumber: UITextField!
#IBOutlet weak var txtId: UITextField!
#IBOutlet weak var txtAmountPercent: UITextField!
#IBOutlet weak var lblTotal: UILabel!
#IBOutlet weak var lblSeparator: UILabel!
#IBOutlet weak var lblPercent: UILabel!
#IBOutlet weak var btnExpenseType: UIButton!
#IBOutlet weak var btnCostCenter: UIButton!
#IBOutlet weak var switchID: UISwitch!
#IBAction func btnExpenseTypePressed(_ sender: Any) {
debugPrint("En btnExpenseTypePressed")
self.delegate?.btnExpenseTypePressed(at: indexPath)
debugPrint("El INDEX \(indexPath)")
}
#IBAction func btnCostCenterPressed(_ sender: Any) {
debugPrint("En btnCostCenterPressed")
self.delegate?.btnCostCenterPressed(at: indexPath)
debugPrint("El INDEX \(indexPath)")
}
#IBAction func amountEditedChanged(_ sender: Any) {
debugPrint("En amountEditedChanged")
self.delegate?.amountEditedChanged(at: indexPath)
lblTotal.text = txtAmountNumber.text
}
#IBAction func switchChanged(_ sender: Any) {
debugPrint("En value changed")
self.delegate?.switchChanged(at: indexPath)
if switchID.isOn {
debugPrint("Dentro if")
txtId.text = ""
txtId.isEnabled = false
} else {
txtId.isEnabled = true
}
}
}
I am using SWIFT 3.
I believe the error comes from a missunderstanding of what you want to do and what you are acctually doing.
You want: Change one value in one cell
You do: Change one value in all cells ON cell creation.
When you call: self.tableView.reloadData() in unc btnExpenseTypePressed(at index: IndexPath) iOS calls
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) again and again skipping the `firstTableLoad = false` and loading all the tableviewCells with the same value.
You have also set the index to 0 in DataManager.costsCenter[0] which will mean that all the cells on creation will have the same value.
My suggestion: Do your changes in:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
}
If by any chance this doesn't help you check clean the cell in :
override func prepareForReuse()
{
super.prepareForReuse()
}
or just set it like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell? = UITableViewCell()
if tableView == self.tableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! ExpenseDetailCell
cell.selectionStyle = .none
cell.delegate = self
cell.setMyCustomText("")...
}
return cell
}

Swift 2 can not add a slider to a UITableView Cell

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

Resources