画面にUITextViewがあり、ユーザーは2行のみを入力する必要があり、2行目のユーザーがリターンキーを押すとDoneになります。
UITextViewで行の数を制限するにはどうすればよいですか?たくさん検索した結果、役に立たなかった!
私はスウィフトのためにこの答えを見つけました:
locationNoteTextView.textContainer.maximumNumberOfLines = 2
self.locationNoteTextView.textContainer.lineBreakMode = NSLineBreakMode.ByClipping
この方法では、ユーザーは無限大の文字を入力できますが、画面には2行しか表示されません。
したがって、textViewのテキストを印刷しようとすると、災害テキストが見つかります。
textView:shouldChangeTextInRange:replacementText:
を実装する必要があります。このメソッドは、テキストが変更されるたびに呼び出されます。 textプロパティを使用して、テキストビューの現在のコンテンツにアクセスできます。
渡された範囲と[textView.text stringByReplacingCharactersInRange:range withString:replacementText]
を使用した置換テキストから新しいコンテンツを構築します。
次に、行数をカウントしてYES
を返し、変更を許可するか、NO
で変更を拒否できます。
編集: OPリクエストの場合:
Swift:
func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize {
return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
var textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset))
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding;
let boundingRect = sizeOfString(newText, constrainedToWidth: Double(textWidth), font: textView.font!)
let numberOfLines = boundingRect.height / textView.font!.lineHeight;
return numberOfLines <= 2;
}
Obj-C
- (CGSize) sizeOfString:(NSString*)str constrainedToWidth:(CGFloat)width andFont:(UIFont*)font
{
return [str boundingRectWithSize:CGSizeMake(width, DBL_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: font}
context:nil].size;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
CGFloat textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset));
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding;
CGSize boundingRect = [self sizeOfString:newText constrainedToWidth:textWidth andFont:textView.font];
int numberOfLines = boundingRect.height / textView.font.lineHeight;
return numberOfLines <= 2;
}
IOS 7以降の場合
textView.textContainer.maximumNumberOfLines = 10;
textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
OR
textView.textContainer.maximumNumberOfLines = 10;
[textView.layoutManager textContainerChangedGeometry:textView.textContainer];
誰かがリアルタイムの行番号カウントを必要とする場合、これがRxSwiftとRxCocoaでそれを行う方法です
let disposeBag = DisposeBag()
textView.rx_text.asDriver().driveNext { text in
let text = text as NSString
var textWidth: CGFloat = CGRectGetWidth(UIEdgeInsetsInsetRect(self.textView.frame, self.textView.textContainerInset))
textWidth -= 2.0 * self.textView.textContainer.lineFragmentPadding
let textAttributes = [NSFontAttributeName: UIFont(name: “Set your font here”, size: 26.0)!]
let boundingRect: CGRect = text.boundingRectWithSize(CGSizeMake(textWidth, 0), options: [NSStringDrawingOptions.UsesLineFragmentOrigin, NSStringDrawingOptions.UsesFontLeading], attributes: textAttributes, context: nil)
let font = UIFont(name: “Set your font here”, size: 26.0)
guard let lineHeight = font?.lineHeight else {return}
let numberOfLines = CGRectGetHeight(boundingRect) / lineHeight
if numberOfLines <= 2 {
self.textView.typingAttributes = [NSFontAttributeName: UIFont(name: “Set your font here”, size: 26.0)!, NSForegroundColorAttributeName: “Set your color here”]
} else {
self.textView.typingAttributes = [NSFontAttributeName: UIFont(name: “Set your font here”, size: 18.0)!, NSForegroundColorAttributeName: “Set your color here”]
}
}.addDisposableTo(disposeBag)
これは@Abhinavの回答ですが、Swiftにあります
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
let textAttributes = [NSFontAttributeName: textView.font]
var textWidth: CGFloat = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset))
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding
let boundingRect: CGRect = newText.boundingRectWithSize(CGSizeMake(textWidth, 0), options: NSStringDrawingOptions.UsesLineFragmentOrigin|NSStringDrawingOptions.UsesFontLeading, attributes: textAttributes, context: nil)
var numberOfLines = CGRectGetHeight(boundingRect) / textView.font.lineHeight;
return numberOfLines <= 2;
}
@AbhinavコードをSwift 5に更新しました。文字数を制限するためのサポートも追加しました。
import UIKit
class ViewController: UIViewController {
@IBOutlet private var textView: UITextView!
private let maxNumberOfLines = 4
private let maxCharactersCount = 100
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
}
extension ViewController: UITextViewDelegate {
private func textView(_ textView: UITextView, newText: String, underLineLimit: Int) -> Bool {
guard let textViewFont = textView.font else {
return false
}
let rect = textView.frame.inset(by: textView.textContainerInset)
let textWidth = rect.width - 2.0 * textView.textContainer.lineFragmentPadding
let boundingRect = newText.size(constrainedToWidth: textWidth,
font: textViewFont)
let numberOfLines = boundingRect.height / textViewFont.lineHeight
let underLimit = Int(numberOfLines) <= underLineLimit
return underLimit
}
func textView(_ textView: UITextView,
shouldChangeTextIn range: NSRange,
replacementText text: String) -> Bool {
let newText = textView.text.replacingCharacters(in: range, with: text)
let underLineLimit = self.textView(textView, newText: newText, underLineLimit: maxNumberOfLines)
let underCharacterLimit = newText.count <= maxCharactersCount
return underLineLimit && underCharacterLimit
}
}
extension String {
func replacingCharacters(in range: NSRange, with string: String) -> String {
let currentNSString = self as NSString
return currentNSString.replacingCharacters(in: range, with: string)
}
func size(constrainedToWidth width: CGFloat, font: UIFont) -> CGSize {
let nsString = self as NSString
let boundingSize = CGSize(width: width, height: .greatestFiniteMagnitude)
return nsString
.boundingRect(with: boundingSize,
options: .usesLineFragmentOrigin,
attributes: [.font: font],
context: nil)
.size
}
}
これは、更新された@Abhinavの回答ですSwift
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard maxLines > 0 else {
return true
}
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let textAttributes = [NSAttributedStringKey.font : textView.font!]
var textWidth: CGFloat = UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset).width
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding
let boundingRect: CGRect = newText.boundingRect(with: CGSize(width: textWidth, height: 0), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: textAttributes, context: nil)
let numberOfLines = Int(floor(boundingRect.height / textView.font!.lineHeight))
return numberOfLines <= maxLines
}
ここでmaxLinesは、textViewを制限する行数です。 0の場合、無制限の行数。