Swift4实现滑动和点击切换View

本文介绍如何在Swift4中实现通过滑动和点击来切换多个控制器的功能,提供了一种简单直接的代码实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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)
        }
        
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值