单击“颜色”navigation bar button
时,会出现15种颜色的下拉菜单。下拉菜单占据屏幕高度和宽度的一半。用户可以向下滚动下拉菜单以查看所有颜色。但是,我现在的代码,单击导航栏按钮时没有任何反应。虽然出于测试目的,当我将滚动视图的背景颜色设置为更加可见时,我看到滚动视图占据了屏幕宽度和高度的一半。当我在view.addSubview(colorView)
的末尾添加colorButtonTapped()
时,我看到下拉显示屏占据了屏幕宽度的一半以及屏幕的所有高度。
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)
}
}
答案 0 :(得分:2)
每次调用scrollView
时都无法更新colorView
和viewWillLayoutSubviews
的帧数。按下按钮即可创建。
下面的代码会将colorView
的{{1}}和x
的框架设置为y
的右边缘,因此不可见< / em>的。两者都应scrollView
将其定位到左边缘。
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)
的{{1}}属性。默认情况下,它已启用,因此它会从colorView
吞下手势识别器。将其设置为isUserInteractionEnabled
和enjoy。
为了在将来克服此类问题,我建议您阅读有关view debugging的更多信息。
scrollView