Swift - 滚动条滑动功能

时间:2017-01-08 02:13:15

标签: ios swift scroll uiscrollview

这是Alibaba.com的ios应用程序。在应用程序中,如果我向左滑动,该栏将向左滚动并显示更多可点击选项。我的问题是,这是怎么做的?

谢谢!

1 个答案:

答案 0 :(得分:0)

我解决了。

1。首先制作一个.xib文件,将其命名为您想要的任何名称,我将其命名为unnamedView,然后添加标签和imageViews。

2. 然后像这样创建UnnamedView类文件并添加所有标签和图像

class unnamedView: UIView {
    @IBOutlet weak var firstButton: UIButton!
    @IBOutlet weak var firstImage: UIImageView!
    @IBOutlet weak var firstLabel: UILabel!
}

3. 然后在主视图控制器中为UnnamedView创建一个数组。

let unnamed = ["title1":"textTitleToLabel","image1":"nameOfImage"]

var unnamedArray = [Dictionary<String,String>]()

4. 然后我将滚动视图添加到主视图控制器

@IBOutlet weak var unnamedScrollView: UIScrollView!

5. 在viewDidLoad()内添加以下内容

unnamedArray = [unnamed]
        unnamedScrollView.isPagingEnabled = true
        unnamedScrollView.contentSize = CGSize(width: unnamedScrollView.bounds.width * CGFloat(unnamedArray.count), height: 100)
        unnamedScrollView.showsHorizontalScrollIndicator = false
        unnamedScrollView.delegate = self
        loadUnnamed()

6。最后在viewDidLoad下面添加了以下内容

func loadCategories() {

        for (index, category) in categoriesArray.enumerated() {
            if let unnamedView = Bundle.main.loadNibNamed("unnamedView", owner: self, options: nil)?.first as? unnamedView {

                unnamedView.firstImage.image = UIImage(named: category["image1"]!)
                unnamedView.firstLabel.text = category["title1"]

                unnamedView.firstButton.tag = index
                unnamedView.firstButton.addTarget(self, action: #selector(ViewController.gotoCategory(sender:)), for: .touchUpInside)

                unnamedScrollView.addSubview(unnamedView)
                unnamedView.frame.size.width = self.view.bounds.size.width
                unnamedView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width

            }
        }
    }

    func gotoCategory (sender:UIButton) {
        print("The user wants to buy feature \(sender.tag)")
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let newViewController = storyBoard.instantiateViewController(withIdentifier: "tableView")
        self.present(newViewController, animated: true, completion: nil)
    }

而且,如果你想添加页面控制点,只需要这个。

@IBOutlet weak var featurePageControl: UIPageControl!

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let page = scrollView.contentOffset.x / scrollView.frame.size.width
    featurePageControl.currentPage = Int(page)
}