在操场上以编程方式创建可滚动的下拉菜单无法正确显示(iOS / Swift)

时间:2019-05-24 09:49:49

标签: swift drop-down-menu

我是Swift的新手,正在尝试在操场上编写可滚动的下拉UI。 我参考了关于stackoverflow的源代码,并在操场上对其进行了修改。 但是,它始终显示黑屏。 有人可以帮我吗?

import UIKit
import PlaygroundSupport

class ViewController: UIViewController, UIScrollViewDelegate {

    var colorView: UIView!
    var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        colorView = UIView()
        colorView.backgroundColor = .white
        scrollView = UIScrollView()
        scrollView.backgroundColor = .brown
        let colorButton = UIBarButtonItem(title: "Colors", style: .plain, target: self, action: #selector(colorButtonTapped))

        colorButton.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0), NSAttributedString.Key.foregroundColor: UIColor.blue], for: UIControl.State())
        navigationController?.navigationBar.topItem?.rightBarButtonItem = colorButton

    }

    @objc func colorButtonTapped() {

        let colorOptions = ["Blue", "Black", "Red", "Green", "Yellow", "Purple", "Orange", "Pink", "Magenta", "Lavender", "Beige", "Tan", "Burgundy", "Eggshell", "Brown"]

        let y = (navigationController?.navigationBar.frame.height)! + UIApplication.shared.statusBarFrame.height
        scrollView.frame = CGRect(x: UIScreen.main.bounds.width / 2.0, y: y, width: UIScreen.main.bounds.width / 2.0, height: UIScreen.main.bounds.height / 2.0)
        scrollView.delegate = self
        scrollView.isScrollEnabled = true

        let buttonHeight: CGFloat = UIScreen.main.bounds.height / 15
        let contentHeight: CGFloat = CGFloat(colorOptions.count) * buttonHeight
        colorView.frame = CGRect(x: 0, y: 0, width: scrollView.frame.width, height: contentHeight)
        //colorView.layer.cornerRadius = 8.0
        colorView.clipsToBounds = true
        colorView.isUserInteractionEnabled = false

        scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width / 2.0, height: contentHeight)

        for (index, title) in colorOptions.enumerated() {
            let button = UIButton(type: .custom)
            button.backgroundColor = .red
            button.frame = CGRect(x: 0, y: buttonHeight * CGFloat(index), width: UIScreen.main.bounds.width / 2.0, height: buttonHeight)
            button.setTitle(title, for: .normal)
            colorView.addSubview(button)
        }
        scrollView.addSubview(colorView)
        view.addSubview(scrollView)
    }
} 

PlaygroundPage.current.liveView = ViewController()

0 个答案:

没有答案