获取TextView的内容高度

通过分析`textView.sizeThatFits(CGSize)`方法,了解到该方法默认返回视图的现有尺寸,子类可重写以根据布局需求定制大小。例如,UISwitch返回固定尺寸,UIImageView返回显示图片的尺寸。然而,此方法不会改变视图本身大小。在Xcode 7.3.1中,可以使用Swift编写方法来获取UITextView的内容高度。

先看下关键的方法
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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值