ios Changing UIScrollView scrollbar color to different colors

后端 未结 17 2433
我在风中等你
我在风中等你 2020-12-05 07:16

How can we change color of UIScrollview\'s scroll indicator to something like blue, green etc.

I know we can change it to white, black. But other then these colors.

17条回答
  •  我在风中等你
    2020-12-05 07:38

    Based on the answer of @Alex (https://stackoverflow.com/a/58415249/3876285), I'm posting just a little improvement to change the color of scroll indicators.

    extension UIScrollView {
    
        var scrollIndicators: (horizontal: UIView?, vertical: UIView?) {
    
            guard self.subviews.count >= 2 else {
                return (horizontal: nil, vertical: nil)
            }
    
            func viewCanBeScrollIndicator(view: UIView) -> Bool {
                let viewClassName = NSStringFromClass(type(of: view))
                if viewClassName == "_UIScrollViewScrollIndicator" || viewClassName == "UIImageView" {
                    return true
                }
                return false
            }
    
            let horizontalScrollViewIndicatorPosition = self.subviews.count - 2
            let verticalScrollViewIndicatorPosition = self.subviews.count - 1
    
            var horizontalScrollIndicator: UIView?
            var verticalScrollIndicator: UIView?
    
            let viewForHorizontalScrollViewIndicator = self.subviews[horizontalScrollViewIndicatorPosition]
            if viewCanBeScrollIndicator(view: viewForHorizontalScrollViewIndicator) {
                horizontalScrollIndicator = viewForHorizontalScrollViewIndicator.subviews[0]
            }
    
            let viewForVerticalScrollViewIndicator = self.subviews[verticalScrollViewIndicatorPosition]
            if viewCanBeScrollIndicator(view: viewForVerticalScrollViewIndicator) {
                verticalScrollIndicator = viewForVerticalScrollViewIndicator.subviews[0]
            }
            return (horizontal: horizontalScrollIndicator, vertical: verticalScrollIndicator)
        }
    
    }
    

    If you don't add .subviews[0], you will get the deeper view and when you try to change the color of the indicator, this will appear with a weird white effect. That's because there is another view in front of it:

    By adding .subviews[0] to each indicator view, once you try to change the color by calling:

    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        DispatchQueue.main.async() {
            scrollView.scrollIndicators.vertical?.backgroundColor = UIColor.yourcolor
        }
    }
    

    You will access to the first view and change the color properly:

    Kudos to @Alex who posted a great solution

提交回复
热议问题