2015-12-26 2 views
1

Я хотел создать маленький UIPickerView, который хорошо выглядит в портретном и альбомном формате, и он сработал ... вроде. Я добавляю pickerView после нажатия кнопки и спрятал его, когда закончил. PickerView работает правильно:Программно создайте UIPickerView, который работает в ландшафте и портрете

  • При запуске приложения в портретном или в альбомном и кнопочный без изменения ориентации
  • Когда у меня есть pickerView на экране, изменение ориентации работает нормально, изменение размера pickerView

Но это не очень хорошо работает при запуске в одной ориентации и изменения ориентации, прежде чем нажать на кнопку, чтобы показать pickerView, затем показывает этот вид вещей: in portait orientation in paysage orientation

Вот код (Single View Application, с помощью всего одной кнопки в раскадровке: 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() } 
} 

Я потерял, я не понимаю, что я могу изменить чтобы заставить его работать

+1

Вместо использования макета фрейма я бы использовал автоматический макет и просто изменял константу ограничения при анимации в/из. Вы можете центрировать выборщик горизонтально. Вам также не нужно будет слушать изменения ориентации - автоматический макет позаботится об этом для вас. – Joey

ответ

1

Спасибо, я сделал это с ограничением (это просто не очень просто), как этот импорт UIKit

класс myViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var myButton: UIButton! 
var myPickerView: UIPickerView! = UIPickerView() 
var activePickerView: Int = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 
    myPickerView.tag = 1 
    myPickerView.delegate = self 
} 

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.translatesAutoresizingMaskIntoConstraints = false 

     self.view.addSubview(myPickerView) 
     let margins = self.view.layoutMarginsGuide 

     let topC = myPickerView.topAnchor.constraintEqualToAnchor(topLayoutGuide.topAnchor, constant: 100.0) 
     let leadingC = myPickerView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor) 
     let trailingC = myPickerView.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor) 
     let heightC = myPickerView.heightAnchor.constraintEqualToConstant(0.0) 
     heightC.identifier = "height" 
     NSLayoutConstraint.activateConstraints([topC, leadingC, trailingC, heightC]) 

     self.view.layoutIfNeeded() 
     myPickerView.setNeedsLayout() 
     heightC.constant = 162.0 

     UIView.animateWithDuration(0.5, delay:0.0, options:UIViewAnimationOptions.CurveEaseInOut, animations:{ 
      self.view.layoutIfNeeded() 
      }, completion: { _ in 
     }) 
    } 
    else 
    { 
     self.selectPickerView() 
    } 
} 

func selectPickerView(){ 
    if (activePickerView == myPickerView.tag) 
    { 
     let _ = myPickerView.selectedRowInComponent(0) 

     for constraint in myPickerView.constraints 
     { 
      if constraint.identifier == "height" 
      { constraint.constant = 0.0 } 
     } 
     myPickerView.setNeedsLayout() 

     UIView.animateWithDuration(0.5, delay:0.0, options:UIViewAnimationOptions.CurveEaseInOut, animations:{ 
      self.view.layoutIfNeeded() 
      }, completion:{ _ in 
       self.myPickerView.removeConstraints(self.myPickerView.constraints) 
       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() 
} 

} 

Мне не нравится анимация, которая отбрасывает pickerView (я не знаю, почему это не является полной противоположностью отображению), но это работает. Я, вероятно, изменю его, используя непрозрачный вид, чтобы охватить pickerView в будущем.