【发布时间】:2015-12-26 23:56:50
【问题描述】:
我想创建一个最小的 UIPickerView,它在纵向和横向格式中看起来都不错,而且它工作......有点。 我按下按钮后添加了pickerView,完成后将其隐藏。 pickerView 工作正常:
- 当我以纵向或横向启动应用程序并按下按钮而不改变方向时
- 当我在屏幕上显示 pickerView 时,更改方向可以正常工作,pickerView 会更改大小
但是在一个方向启动并在单击按钮以显示pickerView之前更改方向时效果不佳,然后会显示以下内容: in portait orientation in paysage orientation
这是代码(单视图应用程序,情节提要中只有一个按钮:myButton,带有触摸动作 touchMyButton)
class myViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var myButton: UIButton!
var myPickerView: UIPickerView! = UIPickerView(frame:CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.width, 162))
var activePickerView: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
myPickerView.tag = 1
myPickerView.delegate = self
myPickerView.autoresizingMask = [.FlexibleWidth]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func touchMyButton(sender: AnyObject) {
if (activePickerView == 0)
{
activePickerView = myPickerView.tag
myPickerView.selectRow(5, inComponent:0, animated:false)
myPickerView.backgroundColor = UIColor.init(white:0.80, alpha:0.80)
myPickerView.frame = CGRectMake(0.0, 100.0, UIScreen.mainScreen().bounds.width, 0.0)
self.view.layoutIfNeeded()
self.view.addSubview(myPickerView)
myPickerView.setNeedsDisplay()
UIView.animateWithDuration(0.5, delay:0.0, options:UIViewAnimationOptions.CurveEaseInOut, animations:{
self.view.layoutIfNeeded()
self.myPickerView.frame = CGRectMake(0.0, 100.0, self.myPickerView.frame.width, 162)
}, completion: { _ in
})
}
else
{
self.selectPickerView()
}
}
func selectPickerView(){
if (activePickerView == myPickerView.tag)
{
let _ = myPickerView.selectedRowInComponent(0)
let framePV = self.myPickerView.frame
UIView.animateWithDuration(0.5, delay:0.0, options:UIViewAnimationOptions.CurveEaseInOut, animations:{
self.view.layoutIfNeeded()
self.myPickerView.frame = CGRectMake(0.0, framePV.origin.y, framePV.width, 0.0 )
}, completion:{ _ in
self.myPickerView.removeFromSuperview()
})
}
activePickerView = 0
}
// MARK: UIPickerViewDataSource methods
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{ return 1 }
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{ return 10 }
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{ return "Row \(row)" }
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
activePickerView = pickerView.tag
selectPickerView()
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation)
{ self.view.layoutIfNeeded() }
}
我迷路了,我看不出我可以改变什么来让它工作
【问题讨论】:
-
我不会使用框架布局,而是使用自动布局,并在动画输入/输出时简单地修改约束的
constant。您可以水平居中选择器视图。您也不需要听方向变化 - 自动布局会为您处理。
标签: ios swift ios9 uipickerview screen-rotation