Created
June 19, 2018 09:08
-
-
Save WedgeSparda/cc31cdfe72fb7eb59104caf3766b2653 to your computer and use it in GitHub Desktop.
Flexible UITextView with minimum and maximum number of lines using AutoLayout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class FlexibleTextView: UITextView { | |
// MARK: - Properties | |
var minNumberOfLines: Int = 5 { | |
didSet { | |
if minNumberOfLines > maxNumberOfLines { | |
minNumberOfLines = oldValue | |
} | |
} | |
} | |
var maxNumberOfLines: Int = 10 { | |
didSet { | |
if maxNumberOfLines < minNumberOfLines { | |
maxNumberOfLines = oldValue | |
} | |
} | |
} | |
private var heightConstraint: NSLayoutConstraint! | |
private var minHeight: CGFloat { | |
return font!.lineHeight * CGFloat(minNumberOfLines) | |
} | |
private var maxHeight: CGFloat { | |
return font!.lineHeight * CGFloat(maxNumberOfLines) | |
} | |
// MARK: - Lifecycle and Setup | |
override init(frame: CGRect, textContainer: NSTextContainer?) { | |
super.init(frame: frame, textContainer: textContainer) | |
setup() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
setup() | |
} | |
deinit { | |
NotificationCenter.default.removeObserver(self) | |
} | |
private func setup() { | |
isScrollEnabled = false | |
NotificationCenter.default.addObserver(self, | |
selector: #selector(updateHeightConstraintIfNeeded), | |
name: .UITextViewTextDidChange, | |
object: nil) | |
heightConstraint = heightAnchor.constraint(equalToConstant: minHeight) | |
heightConstraint.isActive = true | |
} | |
@objc func updateHeightConstraintIfNeeded() { | |
let width = frame.width | |
let newSize = sizeThatFits(CGSize(width: width, | |
height: CGFloat.greatestFiniteMagnitude)) | |
let height = min(max(newSize.height, minHeight), maxHeight) | |
isScrollEnabled = height == maxHeight | |
heightConstraint.constant = height | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment