【问题标题】:Scroll view with page control to display images in iOS使用页面控件滚动视图以在 iOS 中显示图像
【发布时间】:2016-12-04 02:10:28
【问题描述】:

我正在尝试使用 Swift 实现带有页面控件的滚动视图以在 iOS 中显示图像,以获得如下输出:

这里的滚动视图是另一个视图控制器的一部分。 我用谷歌搜索但没有帮助获得所需的输出。 谁能帮帮我?

【问题讨论】:

  • 请澄清您的问题。另外,请提供代码示例,展示您如何尝试实现请求的功能。

标签: ios swift uiscrollview uipagecontrol


【解决方案1】:

答案有点晚了。所以,可能对其他人有帮助:

Swift 3x:

首先,给这样的委托:

class YOUR_VIEW_CONTROLLER: UIViewController, UIScrollViewDelegate 

现在像这样连接UIScrollViewUIPageControl的出口:

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pageControl: UIPageControl!

注意:我正在使用颜色数组。您可以使用图像数组。

var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)

现在只需将以下代码复制并粘贴到您的课程中:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    configurePageControl()

    self.view.bringSubview(toFront: pageControl)
    scrollView.delegate = self
    self.view.addSubview(scrollView)
    for index in 0..<4 {

        frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
        frame.size = self.scrollView.frame.size

        let subView = UIView(frame: frame)
        subView.backgroundColor = colors[index]
        self.scrollView.addSubview(subView)
    }

    self.scrollView.isPagingEnabled = true


    self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)

    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

}

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.
    self.pageControl.layer.zPosition = 1

    self.pageControl.numberOfPages = colors.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.red
    self.pageControl.pageIndicatorTintColor = UIColor.black
    self.pageControl.currentPageIndicatorTintColor = UIColor.green
    self.view.addSubview(pageControl)

}

// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
    scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 2016-08-14
    • 2016-11-24
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多