I have a UISlider in a custom UITableViewCell.
When I look at the size of the slider in awakeFromNib
the .frame
property shows the size of the slider as it was set in the storyboard, not the final size as it is drawn when the view appears.
I had thought all of that set up was done in awakeFromNib
but the size of the slider seems to change between awakeFromNib and its final appearance.
I found a similar question from 2015 that had an answer posted but was not actually resolved.
UITableViewCell: understanding life cycle
I also found a similar question from 2016, but that one doesn't seem to apply to my situation.
Swift UITableViewCell Subview Layout Updating Delayed
I have added a screen capture of my constraints as set in the storyboard.
We don't know the size of the cell (and its UI components) until
layoutSubviews()
So, assuming you are setting the arrow positions as percentages, implement
layoutSubviews()
in your cell class along these lines:I'm assuming all of your rows will have the same "time range" for the slider, so we can get something like this (I set the thumb tint to translucent and the arrow y-positions so we can see the alignment):
For a complete example (to produce that output), use this Storyboard https://pastebin.com/nUZFMtGN (had to move it since this answer became too long) - and this code:
Edit
If we want, we can get rid of the position calculations in
layoutSubviews()
altogether...Let's start with a custom slider thumb image, which we can generate at run-time using an SF Symbol - the background will be clear:
If we use that with
.setThumbImage(arrowThumb, for: [])
, it will look like this (I've given it a translucent background for clarity):Now we could, for example, set the slider's:
and then set the value to the time.
So, we can use one for the "start time" and overlay another one for the "end time":
If we then set:
on both sliders, we get this:
We'll set
.isUserInteractionEnabled = false
for both of those sliders, and overlay an interactive slider on top:Debug View Hierarchy:
When we remove the translucent background:
At this point, we no longer need to do anything in
layoutSubviews()
... we just set the.value
of the "startMarkerSlider" and the "endMarkerSlider" and the arrow-markers will be automatically positioned.Here's example code for that approach - all code, no
@IBOutlet
or@IBAction
connections...Table View Cell class
Example controller class
Note that I also changed the approach to using the data, so we're dealing directly with
Date
objects.