Hello, I am currently learning and developing my first iOS app and I have created a custom UITableViewCell using a XIB file in which I have integrated a UISlider and a SegmentedControl button.
What I want to accomplish is the first time the table loads up, the UISlider is disabled - I accomplish this in awakeFromNib
and it also corresponds to the 0 value selection of the SegmentedControl.
Then when a user touches "One" or "Two" on the SegmentedControl I want to enable the UISlider.
I am using a delegated protocol to send the indexPath of the selected cell to my ViewController:
extension ViewController: AccountCellDelegate {
func segmentControlSelected(at index: IndexPath, segmentValue: Int, slider: UISlider) {
slider.isEnabled = (segmentValue != 0)
myTableView.reloadRows(at: [index], with: .none)
}
The problems with this implementation are that I have to click twice on a SegmentedControl button to see its value selected and the UISlider still does not change its appeareance from "faded out - disabled" to normal - enabled unless I click on it. Do you have any idea if reloadRows(at:with:) is the correct way to refresh the cell so that the UISlider appeareance is correctly displayed?
if reloadRows(at:with:) is the correct way to refresh the cell
reloadRows does what you have defined in
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
So please show this func in your code.
A common mistake is to think that the cell is a data storage. It is not.
So you have to store the status of slider in the dataSource. This dataSource is an array of some struct, like
struct MyCellData {
var someText: String = ""
var sliderOn: Bool = false
}
var myData: [MyCellData] = []
You initialize myData
as needed in viewDidLoad, with the exact number of cells.
You have to change your func into
func segmentControlSelected(at index: IndexPath, segmentValue: Int, slider: UISlider) {
myData[index.row].sliderOn = (segmentValue != 0)
myTableView.reloadRows(at: [index], with: .none)
}
I assume you have defined an IBOulet for slider
@IBOutlet weak var slider : UISlider!
Then cellForRowAt should look like
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Fetch a cell of the appropriate type.
let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath) as! MyCellType
// Configure the cell’s contents.
cell.textLabel!.text = myData[index.row].someText
cell.slider.isEnabled = myData[index.row].sliderOn
return cell
}