如何在Swift 3中制作下拉菜单

4
如何使用Swift 3在iOS中实现下拉菜单,如下图所示:enter image description here 我已经搜索了SO的问题,但他们更喜欢使用UIPicker,而我希望实现这个。是否可以通过使用表格视图来实现此类型?
而且我需要从下拉菜单中选择日期:
如何按如下所示在表格视图中显示日期?

enter image description here


您可以使用表格创建下拉菜单。您可以找到许多下拉菜单的演示。但我也建议使用Picker来选择日期,而不是使用表格。 - Surjeet Singh
3个回答

9

有许多下拉框的演示和样例,你可以通过使用tableView实现这一点,只需在用户点击按钮时使用tableView即可。 或者你可以使用这个 https://cocoapods.org/pods/DropDown

let dropDown = DropDown()

// The view to which the drop down will appear on
dropDown.anchorView = view // UIView or UIBarButtonItem

// The list of items to display. Can be changed dynamically
dropDown.dataSource = ["Car", "Motorcycle", "Truck"]

Optional properties:

// Action triggered on selection
dropDown.selectionAction = { [unowned self] (index: Int, item: String) in
  print("Selected item: \(item) at index: \(index)")
}

// Will set a custom width instead of the anchor view width
dropDownLeft.width = 200
Display actions:

dropDown.show()
dropDown.hide()

您可以下载最新版本,该版本可与最新的Swift版本配合使用。 - Optimus

6

(Swift 3)将文本框和UIPickerView添加到故事板中,然后将委托和数据源添加到UIPickerView,并将委托添加到文本框。请参考视频进行操作。 https://youtu.be/SfjZwgxlwcc

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {


@IBOutlet weak var textBox: UITextField!
@IBOutlet weak var dropDown: UIPickerView!


var list = ["1", "2", "3"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


public func numberOfComponents(in pickerView: UIPickerView) -> Int{
    return 1

}

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

    return list.count

}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    self.view.endEditing(true)
    return list[row]

}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    self.textBox.text = self.list[row]
    self.dropDown.isHidden = true

}

func textFieldDidBeginEditing(_ textField: UITextField) {

    if textField == self.textBox {
        self.dropDown.isHidden = false
        //if you dont want the users to se the keyboard type:

        textField.endEditing(true)
    }

}
}

-2

您可以使用苹果的默认下拉菜单。

请查看这里详情


2
这是针对iOS 14+的。 - Daniel Beltrami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接