Đây là một giải pháp cho Swift 4 (dựa trên Arie Litovsky câu trả lời), bạn có thể đặt mã này vào textViewDidChange(_ textView: UITextView)
phương thức ủy quyền:
Chia tỷ lệ phông chữ xuống:
while (textView.contentSize.height > textView.frame.size.height) {
guard let fontName = textView.font?.fontName, let fontSize = textView.font?.pointSize else {return}
if fontSize < 12 {
return
}
textView.font = UIFont(name: fontName, size: fontSize - 1)
textView.layoutIfNeeded()
}
Và nhân rộng phông chữ:
while (textView.contentSize.height < textView.frame.size.height) {
guard let fontName = textView.font?.fontName, let fontSize = textView.font?.pointSize else {return}
if fontSize > 15 {
return
}
textView.font = UIFont(name: fontName, size: fontSize + 1)
textView.layoutIfNeeded()
}
Bạn có thể thay đổi fontSize < 12
và fontSize > 15
để phù hợp với nhu cầu của bạn trong tối thiểu và kích thước phông chữ tối đa.
Ah, có bất kỳ mã mẫu nào ở đó thực hiện việc này không? Tôi nhìn quanh và không thể tìm thấy gì cả. Cám ơn rất nhiều! –
Tôi không biết bất kỳ mã mẫu nào; Tôi đã không bao giờ nghe nói về bất cứ ai cố gắng làm điều này trước đây. –