「色」navigation bar button
をクリックすると、15色のドロップダウンメニューが表示されます。ドロップダウンは画面の高さと幅の半分を占めます。ユーザーはドロップダウンを下にスクロールしてすべての色を表示できます。しかし、私は今すぐ持っているコードは、ナビゲーションバーのボタンをクリックすると何も起こりません。テスト目的のために、スクロールビューの背景色をより目立つように設定すると、スクロールビューが画面の幅と高さの半分を占めていることがわかります。 view.addSubview(colorView)
をcolorButtonTapped()
の末尾に追加すると、ドロップダウンディスプレイが画面の幅の半分と画面の高さの半分を占めることがわかります。スクロール可能なドロップダウンメニュー(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)
}
}