Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextview write in Text Center Alignment , swift

I have one Text Editor when I tap to Bold Button

I can write in Bold here is code

txtEditor.typingAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.black/, NSAttributedStringKey.font.rawValue: UIFont.boldSystemFont(ofSize: (txtEditor.font?.pointSize)!)]

I want to have one button when I tap to Button (The Line who I write) I need to in Centre Text Center Alignment and not other Line before

here is code

let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center

but after how will to add this 2 line code in UITextview for typing in Centre Alignment ?

like image 560
Miloo Avatar asked Dec 10 '22 08:12

Miloo


2 Answers

Try this.

extension UITextView {

    func centerText() {
        self.textAlignment = .center
        let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let size = sizeThatFits(fittingSize)
        let topOffset = (bounds.size.height - size.height * zoomScale) / 2
        let positiveTopOffset = max(1, topOffset)
        contentOffset.y = -positiveTopOffset
    }

}

use like this

@IBAction func btnClick(_ sender: Any) {
        textView.centerText()
    }
like image 162
Dixit Akabari Avatar answered Dec 28 '22 16:12

Dixit Akabari


Swift 4+

func textViewDidChange(_ textView: UITextView) { textView.textAlignment = .center }
like image 45
jangjehyun Avatar answered Dec 28 '22 16:12

jangjehyun