美文网首页
swift 广告banner 轮播图

swift 广告banner 轮播图

作者: JW_T | 来源:发表于2019-05-23 16:43 被阅读0次

    很久没有写swift  ,今天简单写个广告轮播图,有问题欢迎留言

    class JWAdvertisingScrollView: UIView , UIScrollViewDelegate {

        private var csScroll:UIScrollView = UIScrollView()

        private var csPagecontroll:UIPageControl = UIPageControl()

        lazy private var  dataArray:NSMutableArray = NSMutableArray()

        private static let ResidenceTime = 5.0

        override init(frame: CGRect) {

            super.init(frame: frame)

            isUserInteractionEnabled = true

            csScroll.frame = self.bounds

            csScroll.scrollsToTop = true

            csScroll.isPagingEnabled = true

            csScroll.isUserInteractionEnabled = true

            csScroll.showsHorizontalScrollIndicator = false

            csScroll.showsVerticalScrollIndicator = false

            addSubview(csScroll)

            csPagecontroll.frame = CGRect(x: self.width/2-30, y: self.height-20, width: 60, height: 20)

            csPagecontroll.pageIndicatorTintColor = UIColor(red: 235.0/255.0, green: 235.0/255.0, blue: 235.0/255.0, alpha: 1)

            csPagecontroll.currentPageIndicatorTintColor = UIColor.red

            csPagecontroll.addTarget(self, action: #selector(scrollToIndex(page:)), for: UIControl.Event.valueChanged)

            addSubview(csPagecontroll)

            let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(singleTapGestureRecognizer))

            tapGesture.numberOfTapsRequired = 1

            csScroll.addGestureRecognizer(tapGesture)

        }

        /* 点击方法

        **/

        @objc private func singleTapGestureRecognizer(){

            print(csScroll)

        }

        //刷新页面

        public func reloadSubviews(data:NSArray?){

            if data == nil {

                return

            }

            if data!.count < 1 {

                return

            }

            dataArray.removeAllObjects()

            let arr = NSMutableArray(array: data!)

            dataArray.addObjects(from: arr as! [Any])

            setUpSubViews()

        }

        private func setUpSubViews(){

            let imageItems:NSArray? = dataArray

            let imgCount:Int = ((imageItems?.count)!)

            if imgCount > 1 {

                csPagecontroll.isHidden = false

                csPagecontroll.numberOfPages = imgCount

            }else{

                csPagecontroll.isHidden = true

                csPagecontroll.numberOfPages = 1

            }

            csScroll.delegate = self

            csPagecontroll.currentPage = 0

            csScroll.contentSize = CGSize(width: self.width * CGFloat(imgCount), height: self.height)

            for aview in csScroll.subviews {

                aview.removeFromSuperview()

            }

            for i in 0 ..< imgCount {

                let imageview:UIImageView = UIImageView(frame: CGRect(x: CGFloat(i)*csScroll.width, y: 0, width: csScroll.width, height: csScroll.height))

                imageview.contentMode = UIView.ContentMode.scaleAspectFill

                let dict:NSDictionary? = (imageItems?.object(at: i) as! NSDictionary)

                if dict != nil {

                    let urlStr:String = dict?.object(forKey: "image") as! String

                    if urlStr.nullObject() == false {

                        imageview.sd_setImage(with: URL(string: urlStr), completed: nil)

                    }

                }

                imageview.clipsToBounds = true

                csScroll.addSubview(imageview)

            }

            csScroll.contentOffset = CGPoint(x: 0, y: 0 )

            start()

        }

        //停止滚动

        private func stop() {

            NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(switchFocusImageItems), object: nil)

        }

        //开始滚动

        private func start() {

            let imageItems:NSArray? = dataArray

            if (imageItems?.count)! > 1 {

                self.perform(#selector(switchFocusImageItems), with: nil, afterDelay: JWAdvertisingScrollView.ResidenceTime)

            }

        }

        //滚动后执行

        @objc private func switchFocusImageItems() {

            stop()

            let targetX:CGFloat = csScroll.contentOffset.x + csScroll.frame.size.width

            let imageItems:NSArray? = dataArray

            let imgCount:Int = (imageItems?.count)!

            var point_x:Int = Int(Int(targetX/self.width) * Int(self.width))

            if  point_x >= Int((self.width * CGFloat(imgCount))) {

                point_x = 0;

            }

            moveToTargetPosition(targetX: CGFloat(point_x))

            start()

        }

        //设置位置

        private func moveToTargetPosition(targetX:CGFloat){

            csScroll.setContentOffset(CGPoint(x: targetX, y: 0), animated: true)

        }

        required init?(coder aDecoder: NSCoder) {

            fatalError("init(coder:) has not been implemented")

        }

        func scrollViewDidScroll(_ scrollView: UIScrollView) {

            let targetX = csScroll.contentOffset.x

            let imageItems:NSArray? = dataArray

            let imgCount:Int = (imageItems?.count)!

            if targetX >= (self.width * CGFloat(imgCount)) {

                csPagecontroll.currentPage = imgCount - 1

            }else if targetX <= 0 {

                csPagecontroll.currentPage = 0

            }else{

                let page:Int = Int ((scrollView.contentOffset.x + self.width/2.0)/self.width)

                csPagecontroll.currentPage = page

            }

        }

        @objc private func scrollToIndex(page:UIPageControl) {

            let csIndex:Int = page.currentPage

            moveToTargetPosition(targetX: self.width*(CGFloat(csIndex)))

            page.currentPage = csIndex

        }

        /*

        // Only override draw() if you perform custom drawing.

        // An empty implementation adversely affects performance during animation.

        override func draw(_ rect: CGRect) {

            // Drawing code

        }

        */

    }

    //  调用方法

    let adview = JWAdvertisingScrollView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenW/2))

                adview.reloadSubviews(data: adsArray)

    相关文章

      网友评论

          本文标题:swift 广告banner 轮播图

          本文链接:https://www.haomeiwen.com/subject/fnsbzqtx.html