terenceLuffy / AppStoreStyleHorizontalScrollView

App store style horizontal scroll view
660 stars 73 forks source link

How make elements centered if they all in bounds of scrollview? #2

Open andrewSvsg opened 8 years ago

andrewSvsg commented 8 years ago

Now this situation [_item1_item2_item3__ ] I want make like this [item1_item2_item3____]

Thanks!

terenceLuffy commented 8 years ago

The default behaviour is not to centre the sub views, so the current control can't do the job you want. Instead, you can do a little bit change to achieve your target.

Add the following function to ASHorizontalScrollview.swift, and call this function in refreshSubView (before self.contentSize is set) as well as where you want to centre the subviews.

public func centerSubviews() -> CGFloat{
        if let itemLastX = self.items.last?.frame.maxX {
            if itemLastX + self.leftMarginPx < self.frame.size.width {
                let extraGap = (self.frame.size.width - itemLastX - self.leftMarginPx) / 2
                var itemX = self.leftMarginPx + extraGap
                for item in self.items
                {
                    item.frame = CGRectMake(itemX, item.frame.origin.y, item.frame.width, item.frame.height)
                    itemX += item.frame.width + self.itemsMargin
                }
                return itemX - self.itemsMargin + self.leftMarginPx + extraGap;
            }
            return itemLastX - self.itemsMargin + self.leftMarginPx
        }
        return 0
    }