先看下关键的方法
textView.sizeThatFits(CGSize)
然后看官方文档
Asks the view to calculate and return the size that best fits the specified size.
Declaration
SWIFT
func sizeThatFits(_ size: CGSize) -> CGSize
OBJECTIVE-C
- (CGSize)sizeThatFits:(CGSize)size
Parameters
size
The size for which the view should calculate its best-fitting size.
Return Value
A new size that fits the receiver’s subviews.
Discussion
The default implementation of this method returns the existing size of the view. Subclasses can override this method to return a custom value based on the desired layout of any subviews. For example, a UISwitch object returns a fixed size value that represents the standard size of a switch view, and a UIImageView object returns the size of the image it is currently displaying.
This method does not resize the receiver.
Availability
Available in iOS 2.0 and later.
大概的意思,是这个方法默认操作是返回目前view(label啥的都是view)存在的尺寸,子类可以重写这个方法来获得基于想要的尺寸情况下某个自定义的值。像UISwitch 和 UIImageView都是根据当前的view或者图片尺寸来展示的。
这个方法不会调整接收者的大小。
下面写个方法就可以了 Xcode 7.3.1 Swift
/**
获取UITextView 的内容高度
- parameter textView: 目标textView
- parameter textWidth: 目标textview的宽度
- returns: textView的高度
*/
func heightForString(textView:UITextView,textWidth:CGFloat) ->CGFloat
{
//获取想要的view的size 这边是固定宽度为textview的宽度 高度自适应
let getSize:CGSize = textView.sizeThatFits(CGSize.init(width: textWidth, height: CGFloat(MAXFLOAT)))
//获取textView的高度
return getSize.height
}
通过分析`textView.sizeThatFits(CGSize)`方法,了解到该方法默认返回视图的现有尺寸,子类可重写以根据布局需求定制大小。例如,UISwitch返回固定尺寸,UIImageView返回显示图片的尺寸。然而,此方法不会改变视图本身大小。在Xcode 7.3.1中,可以使用Swift编写方法来获取UITextView的内容高度。
2339

被折叠的 条评论
为什么被折叠?



