Search code examples
swiftuitextviewobserversunwind-segue

Vertical Align UITextView from Unwind Segue Swift


Im using a UITextView to display text in a UIView and I would need the text bloc to be vertically aligned inside this view.

To do so I used an observer method I found online and it work pretty well most of the time:

in viewDidLoad:

moodPhrase.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)

then the observer:

//Update phrase content position (vertical alignment)
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {

        var topCorrect : CGFloat = (moodPhrase.frame.height - moodPhrase.contentSize.height);
        topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect / 2
        moodPhrase.contentOffset = CGPoint(x: 0, y: -topCorrect)

    }

my problem is that I have a menu controller that pop over this controller and I'm using unwind segue to go back from the menu to the UITextView controller. When doing so the text bloc goes back to the top of the screen.

@IBAction func prepareForUnwind(segue: UIStoryboardSegue) {
    if(segue.identifier == "CloseMenuSegue"){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

I tried to add up the observer inside the unwind but it has no effect. Do I miss something here?

thanks,


Solution

  • ok, I found it. For those who need an answer to this, simply add whatever adjustment you need in the dismissViewController completion block.

    @IBAction func prepareForUnwind(segue: UIStoryboardSegue) {
        if(segue.identifier == "CloseMenuSegue"){
            self.dismissViewControllerAnimated(true, completion: {
              //your code here
            })
        }
    }