我限制字符的数量取决于textview的大小。我只允许2行,宽度根据设备而异。如何在不进行硬编码的情况下根据设备自动调整字体?
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// Combine the new text with the old
let combinedText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
// Create attributed version of the text
let attributedText = NSMutableAttributedString(string: combinedText)
attributedText.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, attributedText.length))
// Get the padding of the text container
let padding = textView.textContainer.lineFragmentPadding
// Create a bounding rect size by subtracting the padding
// from both sides and allowing for unlimited length
let boundingSize = CGSizeMake(textView.frame.size.width - padding * 2, CGFloat.max)
// Get the bounding rect of the attributed text in the
// given frame
let boundingRect = attributedText.boundingRectWithSize(boundingSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
// Compare the boundingRect plus the top and bottom padding
// to the text view height; if the new bounding height would be
// less than or equal to the text view height, append the text
if (boundingRect.size.height + padding * 1 <= textView.frame.size.height){
return true
}
else {
return false
}
上面的我的代码根据文本视图的宽度来限制字符的数量,但是当在iphone 6上显示从4s写入的文本时,文本会被截断,因为iphone 4s的宽度小于iphone 6
最佳答案
您可以使用类似:
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
获取设备屏幕尺寸
关于ios - TextView字体大小根据设备屏幕自动调整,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32699229/