分类
iOS学习

swift 滚动分段控制器

将ScrollView与SegmentedControl结合使用

视频加载不出来,看了个寂寞(

import UIKit
import Moya
class ViewController: UIViewController {
    var headerSeg = UISegmentedControl(items: [ "通知公告","学籍管理","考试管理","排课选课"
    ,"成绩管理","毕业管理","实践教学","毕业设计","学科竞赛","综合管理"])
    var scrollView = UIScrollView()
    var newslistModel : [MyNewsListModel] = []
    let provider = MoyaProvider<MyNewsListTarget>()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "资讯"
        self.view.backgroundColor = .white
        setLayout()
        self.headerSeg.addTarget(self, action: #selector(tapped), for: .valueChanged)
    }
    
    func setLayout()
    {
        self.headerSeg.frame.origin = CGPoint(x: 0, y: 0)
        self.headerSeg.frame.size.height = 50.0
        self.headerSeg.frame.size.width = 125.0*10
//        self.scrollView.frame.origin = CGPoint(x: 0, y: (self.navigationController?.navigationBar.frame.height ?? 80) + 20)
        self.scrollView.frame = CGRect(x: 0, y: ((self.navigationController?.navigationBar.frame.height ?? 80) + 20), width: self.view.bounds.width, height: 50)
        self.view.addSubview(self.scrollView)
        self.scrollView.addSubview(self.headerSeg)
        scrollView.isScrollEnabled = false
        for i in 0...9
        {
            headerSeg.setWidth(125, forSegmentAt: i)
        }
         self.scrollView.contentSize = CGSize(width: headerSeg.widthForSegment(at: 1)*20, height: 50)
    }
    
    @objc func tapped()
    {
        switch self.headerSeg.selectedSegmentIndex {
        case 0:
            self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        case 1:
            self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        case 2:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1), y: 0), animated: true)
        case 3:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*2, y: 0), animated: true)
        case 4:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*3, y: 0), animated: true)
        case 5:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*4, y: 0), animated: true)
        case 6:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*5, y: 0), animated: true)
        case 7:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*6, y: 0), animated: true)
        case 8:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*7, y: 0), animated: true)
        case 9:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*7, y: 0), animated: true)
        default:
            return
        }
    }
    
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注