2017-01-13 5 views
1

У меня есть контейнер UIView parent, который имеет три подзаголовка: 1 UITextView и 2 кнопки (кнопки находятся поверх UITextView, но содержатся в качестве подзонов контейнера UIView). Когда я обычно представляю родительский UIView на экране, просто внутри UIViewController, кнопки корректно запускают связанные с ними методы действий и функционируют правильно. Однако, когда я представляю UIView внутри контроллера представления, который становится popover, иерархия представлений отображается правильно, но кнопки не запускают связанные с ними методы действий, и ничего не происходит. Есть что-то около UIPopoverPresentationController s и кнопок, которые я не понимаю?UIButton работает нормально, но не в popoverPresentationController

Добавление кнопок к родительскому UIView

func layoutButtons(in parent: UIView) { 
    let speechButton = UIButton(type: .custom) 
    speechButton.frame = CGRect(x: parent.frame.width - 35, y: parent.frame.height - 35, width: 30, height: 30) 
    speechButton.setImage(UIImage(named: "sound_icon"), for: .normal) 
    speechButton.addTarget(self, action: #selector(Textual.textToSpeech), for: UIControlEvents.touchUpInside) 
    parent.addSubview(speechButton) 

    let fontSizeButton = UIButton(type: .custom) 
    fontSizeButton.frame = CGRect(x: textView.frame.width - 75, y: textView.frame.height - 35, width: 30, height: 30) 
    fontSizeButton.setImage(UIImage(named: "font_size_icon"), for: .normal) 
    fontSizeButton.addTarget(self, action: #selector(Textual.toggleFontSize), for: UIControlEvents.touchUpInside) 
    parent.addSubview(fontSizeButton) 

    // wrap text around the bottom buttons 
    let excludeSpeechButton = UIBezierPath(rect: speechButton.frame) 
    let excludeFontSizeButton = UIBezierPath(rect: fontSizeButton.frame) 
    self.textView.textContainer.exclusionPaths = [excludeSpeechButton, excludeFontSizeButton] 
} 

@objc func textToSpeech() { 
    if synth.isPaused { 
     synth.continueSpeaking() 
    } else if synth.isSpeaking { 
     synth.pauseSpeaking(at: .immediate) 
    } else { 
     let speechUtterance = AVSpeechUtterance(string: attributedText.string) 
     speechUtterance.rate = 0.5 
     synth.speak(speechUtterance) 
    } 
} 

@objc func toggleFontSize() { 

    if self.smallFontSizeMode == true { 
     self.smallFontSizeMode = false 
    } else { 
     self.smallFontSizeMode = true 
    } 

    // for each character, multiply the current font size by fontSizeModifier 
    // http://stackoverflow.com/questions/19386849/looping-through-nsattributedstring-attributes-to-increase-font-size 

    self.attributedText.beginEditing() 

    self.attributedText.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, self.attributedText.length), options: NSAttributedString.EnumerationOptions.reverse, using: { (value, range, stop) in 
     if let oldFont = value as? UIFont { 
      var newFont: UIFont? 
      if self.smallFontSizeMode == true { // was big and now toggling to small 
       newFont = oldFont.withSize(oldFont.pointSize/2) 
      } else { // was small and now toggling to big 
       newFont = oldFont.withSize(oldFont.pointSize * 2) 
      } 
      attributedText.removeAttribute(NSFontAttributeName, range: range) 
      attributedText.addAttribute(NSFontAttributeName, value: newFont!, range: range) 
     } 
    }) 

    self.attributedText.endEditing() 

    self.textView.attributedText = self.attributedText 

} 

Вручая UIViewController

func present(viewController: UIViewController, at location: CGRect) { 

    viewController.modalPresentationStyle = .popover 
    parentViewController.present(viewController, animated: true, completion: nil) 

    let popController = viewController.popoverPresentationController 
    popController?.permittedArrowDirections = .any 
    popController?.sourceView = parentView 
    popController?.sourceRect = location 

} 

UPDATE - Я добавил popController?.delegate = viewController в последней строке func present(viewController:at:) и ниже Я добавлено extension UIViewController: UIPopoverPresentationControllerDelegate { }

ответ

0

Чтобы ответить на ваш вопрос, вы должны сообщить ваше ПРЕДСТАВЛЕНИЕ контроллер представления, кому делегировать, поэтому добавь это ниже, и дайте мне знать, если он работает:

popController?.delegate = viewController 
+0

Я обновил этот вопрос, чтобы отразить ваше предложение. Однако он по-прежнему не работает после добавления 'viewController' в качестве делегата и расширения' UIViewController' для соответствия 'UIPopoverPresentationControllerDelegate' –

+0

huh, если ваш popoverPresentationController всплывает в порядке, все UIButton должно работать. Поэтому, не видя своего «viewController», из которого вы выбрали свой popover, я предполагаю, что вы, возможно, допустили некоторые довольно простые ошибки в вашем классе viewController. – Giraffe

Смежные вопросы