2016-08-05 8 views
5

Wiem, jak przedstawić popover z elementu przycisku paska, jak opisano w this answer (dla iPhone'a i iPada).Przedstaw popover z dowolnego punktu kontrolnego w Swift

enter image description here

Chciałbym dodać popover dla dowolnego punktu zakotwiczenia. Inne odpowiedzi SO, które widziałem były dla elementów przycisku paska lub w Objective-C.

Po prostu nauczyłem się, jak to zrobić, więc poniżej dodam własną odpowiedź.

Odpowiedz

17

Aktualizacja dla Swift 3

W serii ujęć, dodać kontroler widoku, który chciałbyś być popover. Ustaw identyfikator Storyboard ID na "popoverId".

enter image description here

dodać również przycisk do głównego kontrolera widoku i zahaczyć o IBAction do następującego kodu.

import UIKit 
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate { 

    @IBAction func buttonTap(sender: UIButton) { 

     // get a reference to the view controller for the popover 
     let popController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popoverId") 

     // set the presentation style 
     popController.modalPresentationStyle = UIModalPresentationStyle.popover 

     // set up the popover presentation controller 
     popController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up 
     popController.popoverPresentationController?.delegate = self 
     popController.popoverPresentationController?.sourceView = sender // button 
     popController.popoverPresentationController?.sourceRect = sender.bounds 

     // present the popover 
     self.present(popController, animated: true, completion: nil) 
    } 

    // UIPopoverPresentationControllerDelegate method 
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { 
     // Force popover style 
     return UIModalPresentationStyle.none 
    } 
} 

Ustawianie sourceView i sourceRect co pozwala wybrać dowolny punkt, aby wyświetlić popover.

To wszystko. Teraz powinno to być coś podobnego, kiedy przycisk zostanie dotknięty.

enter image description here

Dzięki this article o pomoc.

5

rozwiązanie dla Swift 3.1:

Dodaj do ViewController UIPopoverPresentationControllerDelegate delegat:

class OriginalViewController: UIViewController, UIPopoverPresentationControllerDelegate 

Dodaj przycisk do ViewController i beczki na swojej przycisku, nazywają ten kod:

let controller = MyPopViewController() 
    controller.modalPresentationStyle = UIModalPresentationStyle.popover 
    let popController = controller.popoverPresentationController 
    popController?.permittedArrowDirections = .any 
    popController?.delegate = self 
    popController?.sourceRect = (self.myButton?.bounds)! 
    popController?.sourceView = self.myButton 
    self.present(controller, animated: true, completion: nil) 
Powiązane problemy