我添加了一个日期选择器作为 subview ,我期望的是当我按下“更改日期”按钮时,日期选择器会显示在 View 底部。但现实是simulation result .
@IBAction func onUpdateBirthday(sender: UIButton) {
showChooseBirthday()
}
func showChooseBirthday() {
view.addSubview(chooseBirthday)
let bottomConstraint = chooseBirthday.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
let leftConstraint = chooseBirthday.leftAnchor.constraintEqualToAnchor(view.leftAnchor)
let rightConstraint = chooseBirthday.rightAnchor.constraintEqualToAnchor(view.rightAnchor)
let heightContraint = chooseBirthday.heightAnchor.constraintEqualToConstant(60)
NSLayoutConstraint.activateConstraints([bottomConstraint,leftConstraint,rightConstraint,heightContraint])
view.layoutIfNeeded() // re-layout the view
self.chooseBirthday.alpha = 0
UIView.animateWithDuration(0.4) {
self.chooseBirthday.alpha = 1
}
这里是 a part of storyboard .
最佳答案
正如其他人所说,您可以将日期选择器添加到 UITextField。下面是一个例子,希望对你有帮助。 Result here
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var birthdayTextField: UITextField!
var birthdayPicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
configureBirthdayPicker()
}
func configureBirthdayPicker(){
birthdayPicker.datePickerMode = .Date
birthdayPicker.maximumDate = NSDate()
birthdayPicker.tintColor = UIColor.blackColor()
birthdayPicker.backgroundColor = UIColor.groupTableViewBackgroundColor()
let toolBar = UIToolbar()
toolBar.barTintColor = UIColor.groupTableViewBackgroundColor()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor.blueColor()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker:")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelPicker:")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
birthdayTextField.inputView = birthdayPicker
birthdayTextField.inputAccessoryView = toolBar
}
func donePicker(doneclicked:UIButton){
print("done clicked")
birthdayTextField.resignFirstResponder()
}
func cancelPicker(cancelclicked:UIButton){
print("cancel clicked")
birthdayTextField.resignFirstResponder()
}
}
关于ios - subview 的位置不是我所期望的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36808006/