Add datepicker in UIActionsheet using Swift

非 Y 不嫁゛ 提交于 2019-12-21 18:04:42

问题


Is there any way to present the datepicker from UIAlertControllerStyle.ActionSheet ? There is way to add buttons and add actions to those buttons in the ActionSheet, but i couldn't find a solution to add a datepicker or any custom view in the ActionSheet.


回答1:


It is not possible, but you can use a UItextfield input view and accessory view to show and dismiss a datepicker when the user clicks the textfield

class KPDatePickerViewController: UIViewController {
    var datePicker:UIDatePicker!
    @IBOutlet var dateTextField:UITextField!

    override func viewDidLoad() {
        var customView:UIView = UIView (frame: CGRectMake(0, 100, 320, 160))
        customView.backgroundColor = UIColor.brownColor()
        datePicker = UIDatePicker(frame: CGRectMake(0, 0, 320, 160))
        customView .addSubview(datePicker)
        dateTextField.inputView = customView
        var doneButton:UIButton = UIButton (frame: CGRectMake(100, 100, 100, 44))
        doneButton.setTitle("Done", forState: UIControlState.Normal)
        doneButton.addTarget(self, action: "datePickerSelected", forControlEvents: UIControlEvents.TouchUpInside)
        doneButton.backgroundColor = UIColor .blueColor()
        dateTextField.inputAccessoryView = doneButton
    }

    func datePickerSelected() {
        dateTextField.text =  datePicker.date.description
    }
}



回答2:


Yes it is definitely possible to present UIDatePicker in UIAlertController. Check out the following code in Swift 4. I have used this code many a times in Projects and it worked fine.

let dateChooserAlert = UIAlertController(title: "Choose date...", message: nil, preferredStyle: .actionSheet)
dateChooserAlert.view.addSubview(datePicker)
dateChooserAlert.addAction(UIAlertAction(title: "Done", style: .cancel, handler: { action in
        // Your actions here if "Done" clicked...
    }))
let height: NSLayoutConstraint = NSLayoutConstraint(item: dateChooserAlert.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.1, constant: 300)
dateChooserAlert.view.addConstraint(height)
self.present(dateChooserAlert, animated: true, completion: nil)


来源:https://stackoverflow.com/questions/25780599/add-datepicker-in-uiactionsheet-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!