Swift2.2 根据文本字数计算scrollView高度


代码如下



`
import UIKit

class ViewController: UIViewController
{

override func viewDidLoad()
{
    super.viewDidLoad()
    
    let screen_w = UIScreen.mainScreen().bounds.width
    let screen_h = UIScreen.mainScreen().bounds.height
    
    //设置scrollView
    let theScrollView = UIScrollView()
    theScrollView.showsVerticalScrollIndicator = true//scrollView显示纵向滚动条
    theScrollView.showsHorizontalScrollIndicator = false//scrollView不显示横向滚动条
    theScrollView.bounces = false//scrollView滚动到边界没有弹跳缓冲效果
    theScrollView.layer.borderColor = UIColor.greenColor().CGColor//边框颜色
    theScrollView.layer.borderWidth = 2//边框宽度
    theScrollView.frame = CGRectMake(10, 20, screen_w-20, screen_h-20)
    
    //用label承载文本内容即可
    let highLabel = UILabel()
    highLabel.backgroundColor = UIColor.yellowColor()//文本背景色
    highLabel.textColor = UIColor.redColor()//文本字体颜色
    highLabel.numberOfLines = 0//设置label多行显示
    highLabel.font = UIFont.systemFontOfSize(35)//文本字体大小
    highLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail//设置换行模式
    
    highLabel.text = "  Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用。Swift 结合了 C 和 Objective-C 的优点并且不受C兼容性的限制。Swift 采用安全的编程模式并添加了很多新特性,这将使编程更简单,更灵活,也更有趣。Swift 是基于成熟而且倍受喜爱得 Cocoa 和 Cocoa Touch 框架,他的降临将重新定义软件开发。"
    + "\n Swift 的开发从很久之前就开始了。为了给 Swift 打好基础,苹果公司改进了编译器,调试器和框架结构。我们使用自动引用计数(Automatic Reference Counting, ARC)来简化内存管理。我们在 Foundation 和 Cocoa的基础上构建框架栈并将其标准化。Objective-C 本身支持块、集合语法和模块,所以框架可以轻松支持现代编程语言技术。正是得益于这些基础工作,我们现在才能发布这样一个用于未来苹果软件开发的新语言。"
    + "\n Objective-C 开发者对 Swift 并不会感到陌生。它采用了 Objective-C 的命名参数以及动态对象模型,可以无缝对接到现有的 Cocoa 框架,并且可以兼容 Objective-C 代码。在此基础之上,Swift 还有许多新特性并且支持过程式编程和面向对象编程。"

   
    
    
    //MARK:动态计算label高度
    
    //设置highLabel的最大宽和高
    let highLabelMaxSize =  CGSizeMake(screen_w-20, 9999)
    
    //计算highLabel的实际frame
    let realSize = highLabel.sizeThatFits(highLabelMaxSize)//根据highLabel的最大宽和高计算highLabel实际尺寸
    highLabel.frame = CGRectMake(0, 0, realSize.width,realSize.height)
    
    //计算scrollview的内容部分宽度,高度
    theScrollView.contentSize = CGSizeMake(highLabel.frame.width , highLabel.frame.height)
    
    //在scrollview上添加label
    theScrollView.addSubview(highLabel)
    
    //在页面中添加scrollview
    self.view.addSubview(theScrollView)
    

    
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
`

你可能感兴趣的:(Swift2.2 根据文本字数计算scrollView高度)