模仿微博页面,swift版本

如题,对文博页面的简单的模仿,和之前团购那个不一样的是,这个是用代码去添加cell的子控件,还需要计算文本内容所占的大小,还有就是注意到了代理方法的执行是有一定顺序的,以后需要注意
代码部分:

首先是数据的加载,这次的数据的加载和之前的有点不同,除了加载数据之外,还需要计算出控件需要的大小,分成了两个类
//
//  Microblog.swift
//  微博
//
//  Created by admin on 16/1/6.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
//记录下两个lable的字体的大小,方便之后计算
let nameFontSize:CGFloat = 15
let textFontSize:CGFloat = 17
//模型类
class Microblog: NSObject {
    var name:NSString!
    var icon:NSString!
    var text:NSString!
    var picture:NSString!
    var vip:NSNumber!
    //便捷构造器
    convenience init(dic:[String : AnyObject]) {
        self.init()
        self.setValuesForKeysWithDictionary(dic)
    }
}
//
//  MicroblogFram.swift
//  微博
//
//  Created by admin on 16/1/7.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
//控件位置信息类
class MicroblogFram: NSObject {
    let iconFram:CGRect
    let nameFram:CGRect
    let vipFram:CGRect
    let textFram:CGRect
    let pictureFram:CGRect
    let cellHeight:CGFloat
    let microblog:Microblog
    //构造方法
    init(iconFram:CGRect,nameFram:CGRect,vipFram:CGRect,textFram:CGRect,pictureFram:CGRect,cellHeight:CGFloat,microblog:Microblog) {
        self.iconFram = iconFram
        self.nameFram = nameFram
        self.vipFram = vipFram
        self.textFram = textFram
        self.pictureFram = pictureFram
        self.cellHeight = cellHeight
        self.microblog = microblog
    }
    //便捷构造器,使用microblog对象来初始化microblogfram
    convenience init(microblog:Microblog) {
        //间距
        let margin:CGFloat = 10
        //图标fram计算
        let iconFram:CGRect = CGRectMake(10, 10, 50, 50)
        //通过字符串计算字符所需的大小
        let nameSize = microblog.name.boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: NSStringDrawingOptions.UsesFontLeading, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(nameFontSize)], context: nil).size
        let nameX = CGRectGetMaxX(iconFram) + margin
        let nameY = ((iconFram.size.height - nameSize.height) / 2) + margin
        let nameFram = CGRectMake(nameX, nameY, nameSize.width, nameSize.height)
        //vip
        var vipFram = CGRectMake(0, 0, 0, 0)
        if microblog.vip == 1
        {
            let vipSize = CGSizeMake(14, 14)
            let vipX = CGRectGetMaxX(nameFram) + margin
            let vipY = (nameFram.size.height - vipSize.height) / 2 + nameFram.origin.y
            vipFram = CGRectMake(vipX, vipY, vipSize.width, vipSize.height)
        }
        //text
        //通过字符串计算字符所需要占用的大小,注意 NSStringDrawingOptions.UsesLineFragmentOrigin 这个选项会把文字换行的高度计算起来,UsesFontLeading只计算一行的高度
        let textSize = microblog.text.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.size.width - (margin * 2), CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(textFontSize)], context: nil).size
        let textX = margin
        let textY = CGRectGetMaxY(iconFram) + margin
        let textFram = CGRectMake(textX, textY, textSize.width, textSize.height)
        //整个cell的高度
        var cellHeight = CGRectGetMaxY(textFram) + margin
        //picture
        var pictureFram = CGRectMake(0, 0, 0, 0)
        if microblog.picture != nil
        {
            let pictureSize = CGSizeMake(100, 100)
            let pictureX = margin
            let pictureY = CGRectGetMaxY(textFram) + margin
            pictureFram = CGRectMake(pictureX, pictureY, pictureSize.width, pictureSize.height)
            //如果有图片,修改cell高度
            cellHeight = CGRectGetMaxY(pictureFram) + margin
        }
        //初始化类
        self.init(iconFram: iconFram,nameFram: nameFram,vipFram: vipFram,textFram: textFram,pictureFram: pictureFram,cellHeight: cellHeight,microblog:microblog)
    }
    //读取plist中的数据
    class func instanceWithFile()->[MicroblogFram]
    {
        let path:String! = NSBundle.mainBundle().pathForResource("microblog", ofType: "plist")
        let data = NSArray(contentsOfFile: path)
        var microblogs:[MicroblogFram] = []
        for var i = 0;i < data?.count;i++
        {
            microblogs.append(MicroblogFram.init(microblog: Microblog.init(dic: data![i] as! [String : AnyObject])))
        }
        return microblogs
    }
}
自定义cell类,没有用到xib,注意下变量的 didSet 方法
//
//  MicroblogCell.swift
//  微博
//
//  Created by admin on 16/1/6.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
//自定义cell
class MicroblogCell: UITableViewCell {
    var microblogFram:MicroblogFram?
    {
        //当变量发生改变时会触发这个方法
        didSet
        {
            //添加子控件
            self.assignSubviewContent()
            //调整子控件位置
            self.assignSubViewFram()
        }
    }
    //存储子控件的变量
    var nameView:UILabel!
    var iconView:UIImageView!
    var textView:UILabel!
    var pictureView:UIImageView!
    var vipView:UIImageView!
    //快速初始化
    class func instance(tableView:UITableView)->MicroblogCell
    {
        //尝试从缓冲池中读取内容
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil
        {
            cell = MicroblogCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
        }
        let temp = cell as! MicroblogCell
        return temp
    }
    //重写父类的构造方法
    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        //执行父类的构造器
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //执行自己的方法,就是添加子控件
        self.nameView = UILabel()
        self.nameView.font = UIFont.systemFontOfSize(nameFontSize)
        self.iconView = UIImageView()
        self.textView = UILabel()
        self.textView.font = UIFont.systemFontOfSize(textFontSize)
        //文本内容可能需要换行,这里设置下行数
        self.textView.numberOfLines = 0
        self.pictureView = UIImageView()
        self.vipView = UIImageView()
        //添加进父控件
        self.addSubview(self.nameView)
        self.addSubview(self.iconView)
        self.addSubview(self.textView)
        self.addSubview(self.pictureView)
        self.addSubview(self.vipView)
    }
    //这个方法不知道什么用,重写上面构造方法的时候系统自动加上来的
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //给子控件赋值
    func assignSubviewContent()
    {
        self.nameView.text = self.microblogFram?.microblog.name as? String
        self.iconView.image = UIImage(imageLiteral: self.microblogFram?.microblog.icon as! String)
        self.textView.text = self.microblogFram?.microblog.text as? String
        if self.microblogFram?.microblog.picture != nil
        {
            self.pictureView.image = UIImage(imageLiteral: self.microblogFram?.microblog.picture as! String)
        }
        if self.microblogFram?.microblog.vip == 1
        {
            self.vipView.image = UIImage(imageLiteral:  "vip")
            self.vipView.hidden = false
            self.nameView.textColor = UIColor.redColor()
        }
        else
        {
            self.vipView.hidden = true
            self.nameView.textColor = UIColor.blackColor()
        }
    }
    //设置子控件位置大小
    func assignSubViewFram()
    {
        self.nameView.frame = (self.microblogFram?.nameFram)!
        self.iconView.frame = (self.microblogFram?.iconFram)!
        self.textView.frame = (self.microblogFram?.textFram)!
        self.pictureView.frame = (self.microblogFram?.pictureFram)!
        self.vipView.frame = (self.microblogFram?.vipFram)!
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
然后就是在控制器中的调用了
//
//  TableViewController.swift
//  微博
//
//  Created by admin on 16/1/6.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class TableViewController: UITableViewController {

    lazy var microblogs:[MicroblogFram] = MicroblogFram.instanceWithFile()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.microblogs.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = MicroblogCell.instance(tableView)

        cell.microblogFram = self.microblogs[indexPath.row]
        // Configure the cell...

        return cell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.microblogs[indexPath.row].cellHeight
    }
}

标签: swift, ios控件

添加新评论