Miloo
Miloo

Reputation: 127

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 ?

Upvotes: 6

Views: 12031

Answers (2)

jangjehyun
jangjehyun

Reputation: 41

Swift 4+

func textViewDidChange(_ textView: UITextView) { textView.textAlignment = .center }

Upvotes: 4

Dixit Akabari
Dixit Akabari

Reputation: 2547

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()
    }

Upvotes: 12

Related Questions