Swift4实现滑动和点击切换View

滑动和点击切换多个控制器

开发中会遇到需要滑动或者点击切换显示的内容。
类似下面的效果
在这里插入图片描述
直接上代码,比较简单

let screen_width = UIScreen.main.bounds.size.width
let screen_height = UIScreen.main.bounds.size.height

class ViewController: UIViewController {
    
    var currentPosition = 0

    @IBOutlet weak var scrollView: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let firstView:FirstViewController = FirstViewController()
        
        let secondView:SecondViewController = SecondViewController()
        
        let thirdView:ThirdViewController = ThirdViewController()
        
        firstView.view.frame = CGRect(x: 0, y: 0, width: screen_width, height: screen_height)
        secondView.view.frame = CGRect(x: screen_width, y: 0, width: screen_width, height: screen_height)
        
        thirdView.view.frame = CGRect(x: screen_width*2, y: 0, width: screen_width, height: screen_height)
        
        self.scrollView .addSubview(firstView.view)
        self.scrollView.addSubview(secondView.view)
        self.scrollView.addSubview(thirdView.view)
        self.scrollView.contentSize = CGSize(width: 3*screen_width, height: 0)
        
        
    }

    @IBAction func rightBtn_click(_ sender: Any) {
        if currentPosition != 2 {
            currentPosition = 2
            self.scrollView.setContentOffset(CGPoint(x: 2*screen_width, y: 0), animated: true)
        }
        
    }
    @IBAction func centerBtn_click(_ sender: Any) {
        if currentPosition != 1 {
            currentPosition = 1
            self.scrollView.setContentOffset(CGPoint(x: screen_width, y: 0), animated: true)
        }
        
    }
    @IBAction func leftBtn_click(_ sender: Any) {
        if currentPosition != 0 {
            self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        }
        
    }
发布了11 篇原创文章 · 获赞 2 · 访问量 2649
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览