Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

UITextViewの縦方向の中央寄せ

contentSizeをオブザーブして

        textView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

contentSizeに変化があれば、中身を調節する。

    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let textView = object as? UITextView {
            var topCorrect = (textView.bounds.size.height - textView.contentSize.height * textView.zoomScale) / 2
            topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
            textView.contentInset.top = topCorrect
        }
    }

    deinit {
        textView.removeObserver(self, forKeyPath: "contentSize")
    }