我想自动调整UITextView类似于sms-app或whatsapp。我只找到了objective-c的解决方案,示例项目的代码太多了。我在Swift中需要这个。
问:在用户输入带有换行符的消息时,如何按字体大小调整UITextView的大小?
答案 0 :(得分:3)
您可以使用UITextViewDelegate执行此操作。我不知道如何使用AutoLayout实现这一目标。
func textViewDidChange(textView: UITextView)
{
var fixedWidth : CGFloat = textView.frame.size.width
var newSize : CGSize = textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat(MAXFLOAT)))
var newFrame : CGRect = textView.frame
newFrame.size = CGSizeMake(CGFloat(fmaxf((Float)(newSize.width), (Float)(fixedWidth))),newSize.height)
textView.frame = newFrame
}
答案 1 :(得分:0)
var textStorage: NSTextStorage!
var layoutManager: NSLayoutManager!
var textContainer: NSTextContainer!
var textPreview: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textStorage = NSTextStorage()
layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let newTextViewRect = view.bounds
let containerSize = CGSize(width: newTextViewRect.width, height: CGFloat.max + 5)
textContainer = NSTextContainer(size: containerSize)
layoutManager.addTextContainer(textContainer)
textPreview = UITextView(frame: newTextViewRect, textContainer: textContainer)
textPreview.font = UIFont(name: "Helvetica", size: 16)
view.addSubview(textPreview)
configureView()
let length = count(textPreview.text)
let range:NSRange = NSMakeRange(length , 1)
textPreview.scrollRangeToVisible(range)
}
override func viewDidLayoutSubviews() {
textPreview.frame = view.bounds
}