Reputation: 1140
I have a horizontal UIScrollView which is added as a subview inside custom UITableViewCell. For some cases, I want to change the scrollview content offset which I achieve by doing this code
cell.horizontalScrollView.setContentOffset(CGPoint(x: 300, y: cell.horizontalScrollView.contentOffset.y), animated: true)
inside the UITableView
's cellForRowAtIndexPath
function and tableview.reloadData()
is called whenever I needed to scroll it programmatically.
The issue is, this does not work for the first time. ie,
When the tableview is loaded for the first time, the scrollviews inside the visible cells does not get scrolled according to the code. Its offset is just at (0,0). ---- (This is the issue!)
But after that, when I scrolled the tableView
, then the new cells(reused cells) gets updated and scrollviews position gets changed. (which I needed from the start itself!)
So, I want to change the UIScrollView
's initial offset(position) programmatically. How can I achieve that?
Upvotes: 0
Views: 1747
Reputation: 1140
Atlast, I found the solution after sitting for a couple of days!
Had to implement layoutIfNeeded
for the UITableViewCell
inside the cellForRowAtIndexPath
method before setting the contentOffset
for the UIScrollView
.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.layoutIfNeeded()
cell.horizontalScrollView.setContentOffset(CGPoint(x: 300, y: cell.horizontalScrollView.contentOffset.y), animated: false)
return cell
}
Upvotes: 2
Reputation: 65
The best way to implement this is to subclass your cell and then set the content offset in layoutSubviews
method.
Upvotes: 0