頁(yè)控件(UIPageControl)

import UIKit

class ViewController: UIViewController,UIScrollViewDelegate {
    var scrollView:UIScrollView?
    var picArr:[String]?
    var pageControl:UIPageControl?
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        picArr = ["java.png","scala.png","swift.png"]
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
        self.view.addSubview(scrollView!)
        scrollView?.delegate = self
        //設(shè)置內(nèi)容大小
        scrollView?.contentSize = CGSize(width: self.view.bounds.width*3, height: self.view.bounds.height)
        //設(shè)置不顯示滾動(dòng)條
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        //滾動(dòng)時(shí)只能停留到某一頁(yè)
        scrollView?.isPagingEnabled = true
        
        //for循環(huán),枚舉
        for (seg,str) in (self.picArr?.enumerated())! {
            let img = UIImageView(image: UIImage(named: str))
            img.frame = CGRect(x: CGFloat(seg)*self.view.bounds.width, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
            scrollView?.addSubview(img)
        }
        pageControl = UIPageControl(frame: CGRect(x: 80, y: self.view.bounds.height-50, width: 80, height: 30))
        pageControl?.currentPage = 0
        pageControl?.numberOfPages = (self.picArr?.count)!
        pageControl?.addTarget(self, action: #selector(pageControlClick(_ :)), for: .valueChanged)
        
        self.view.addSubview(pageControl!)
        
        
        // Do any additional setup after loading the view, typically from a nib.
        
        
    }
    func pageControlClick(_ page:UIPageControl)
    {
        //根據(jù)點(diǎn)擊的頁(yè)數(shù),計(jì)算scrollView需要顯示的偏移量
        var frame = scrollView?.frame
        frame?.origin.x = (frame?.size.width)! * CGFloat(page.currentPage)
        frame?.origin.y = 0
        //展現(xiàn)當(dāng)前頁(yè)面內(nèi)容
        scrollView?.scrollRectToVisible(frame!, animated:true)
        
    }


    //減速停止的時(shí)候開(kāi)始執(zhí)行
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //通過(guò)scrollView內(nèi)容的偏移計(jì)算當(dāng)前顯示的是第幾頁(yè)
        let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
        //設(shè)置pageController的當(dāng)前頁(yè)
        self.pageControl?.currentPage = page
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容