How would one write this in Swift?
Update: posted the method I'm trying to convert, originally posted a different method that was not what I was trying to covert
This works in Objective C, but not Swift. I get conversion errors when I try to use ceilf
and floorf
with CGFloat
.
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
float pageWidth = 200 + 30; // width + space
float currentOffset = scrollView.contentOffset.x;
float targetOffset = targetContentOffset->x;
float newTargetOffset = 0;
if (targetOffset > currentOffset)
newTargetOffset = ceilf(currentOffset / pageWidth) * pageWidth;
else
newTargetOffset = floorf(currentOffset / pageWidth) * pageWidth;
if (newTargetOffset < 0)
newTargetOffset = 0;
else if (newTargetOffset > scrollView.contentSize.width)
newTargetOffset = scrollView.contentSize.width;
targetContentOffset->x = currentOffset;
[scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
}
To answer from Christian: I was able to rewrite this in Swift. I set everything up as
Float
to do the math then converted toCGFloat
as Christian mentioned was possible. His answer is technically correct, but showing a newer iOS developer how this is written in Swift was what I was looking for.Maybe later for the party, but none of the proposed solutions are viable solution if dealing with iOS11 + Swift4, IMHO.
Below there is a more suitable answer for the problem, fully working with Swift 4.1:
well, that's not work for me, and i get a compromise method, use the
scrollViewDidEndDecelerating
You can use
ceil
orfloor
. Apple now allowsCGFloat
as parameter in common functions like these. For example:So in your example: