單擊「顏色」navigation bar button
時,應顯示15種顏色的下拉菜單。下拉將佔用屏幕高度和寬度的一半。用戶可以向下滾動下拉菜單查看所有顏色。然而,我現在的代碼沒有任何反應,當點擊導航欄按鈕時。儘管出於測試目的,當我將滾動視圖的背景顏色設置爲更明顯時,我發現滾動視圖佔用了屏幕寬度和高度的一半。當我在colorButtonTapped()
的末尾添加view.addSubview(colorView)
時,我看到下拉顯示佔用了屏幕寬度的一半以及屏幕的所有高度。以編程方式創建可滾動下拉菜單(iOS/Swift)
AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: ViewController())
window?.makeKeyAndVisible()
return true
}
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var colorView: UIView!
var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
colorView = UIView()
scrollView = UIScrollView()
let colorButton = UIBarButtonItem(title: "Colors", style: .plain, target: self, action: #selector(colorButtonTapped))
colorButton.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14.0), NSForegroundColorAttributeName: UIColor.black], for: UIControlState())
navigationController?.navigationBar.topItem?.rightBarButtonItem = colorButton
}
func colorButtonTapped() {
let colorOptions = ["Blue", "Black", "Red", "Green", "Yellow", "Purple", "Orange", "Pink", "Magenta", "Lavender", "Beige", "Tan", "Burgundy", "Eggshell", "Brown"]
let buttonHeight: CGFloat = UIScreen.main.bounds.height/15
colorView.layer.cornerRadius = 8
colorView.clipsToBounds = true
//create options button
for (index, title) in colorOptions.enumerated() {
let button = UIButton(type: .custom)
button.backgroundColor = .red
button.frame = CGRect(x: 0, y: buttonHeight * CGFloat(index), width: colorView.frame.width, height: buttonHeight)
button.setTitle(title, for: .normal)
colorView.addSubview(button)
}
scrollView.delegate = self
scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width/2.0, height: UIScreen.main.bounds.height/2.0)
scrollView.addSubview(colorView)
view.addSubview(scrollView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
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)
colorView.frame = CGRect(x: UIScreen.main.bounds.width/2.0, y: y, width: UIScreen.main.bounds.width/2.0, height: UIScreen.main.bounds.height)
}
}