轉載 - swift 純代碼自定義cell(qq聊天界面)

原文鏈接:https://blog.csdn.net/xingyun1992/article/details/51172048

引子

本人也是初學者,如有錯誤,請指正~

網上大多數都是oc語言的例子,swift的比較少,我就寫一篇拋磚引玉

先放張效果圖
效果圖

感覺做起來比Android麻煩百倍,文本高度要自己計算,cell行高也要自己計算。(Android裏面一個wrap_content就都解決了)
爲什麼不用xib自定義呢,我表示那個情況下更加複雜,高度更不知道如何計算、還有圖片拉伸的問題、

開始正文

1.導入圖片,plist文件,字典轉模型

import UIKit

class Msg: NSObject {

    var text :String!
    var time :String!
    var type :NSNumber!

    override init() {
        super.init()
    }

    init(dir : Dictionary<String,AnyObject>) {
        super.init()
        setValuesForKeysWithDictionary(dir)
    }

    func getMsgArray() -> Array<Msg> {
        var array : Array<Msg> = []
        //取到plist文件路徑
        let diaryList:String = NSBundle.mainBundle().pathForResource("messages", ofType:"plist")!
        //取出plist文件數據
        let arraylist = NSMutableArray(contentsOfFile: diaryList)!

        for i in arraylist {
            let msg = Msg(dir: i as! Dictionary<String, AnyObject> )
            array.append(msg)

        }

        return array

    }

}

這裏也弄了很久,oc裏面是沒有Array,只有NSArray,兩者區別大的很,Array很像Java裏面的ArrayList,需要加泛型,並且是一個結構體。關鍵方法setValuesForKeysWithDictionary、模型類的變量類型和名字都必須和plist文件一致!

2.創建自定義cell 繼承UITableViewCell

下面按照純代碼自定義cell的方式一步步創建

2.1 聲明變量,並且初始化

import UIKit

class MsgCodeCell: UITableViewCell {
    var textmsg :UIButton?
    var icon :UIImageView?
    var time :UILabel?
    var screenWdith : CGFloat?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code 

        //xib自定義cell
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //代碼自定義cell的入口方法~
        textmsg = UIButton();
        icon = UIImageView();
        time = UILabel();
        
        //這裏做一些基本屬性設置
        time?.bounds = CGRect(x: 0, y: 0, width: 80, height: 10)
        time?.font = UIFont.boldSystemFontOfSize(12)

        screenWdith = UIScreen.mainScreen().bounds.size.width

        //先不設置frame和content
        contentView.addSubview(textmsg!)
        contentView.addSubview(icon!)
        contentView.addSubview(time!)
    }

初始化後,進行一些基本屬性的設置,如字體,一些已經可以確定的位置大小,具體的位置需要等到外部數據賦值進來才能確定。

3.提供外部方法設置cell內容和內部控件位置

func setMsgModle(msg:Msg) {
        //1.設置時間
        time?.text = msg.time
        time?.center = CGPoint(x: contentView.center.x, y: 10)

        //2.設置頭像
        var textX : CGFloat = 0
        var iconX : CGFloat = 0
        var backimage : UIImage!

        //計算文字寬高!
        let size = NSString(string: msg.text).boundingRectWithSize(CGSizeMake(screenWdith!-140, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin , attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(14)], context: nil).size

        if msg.type == 0 {
            //發送者
            iconX = screenWdith! - 60
            icon?.image = UIImage(named: "me")
            textX = screenWdith! - size.width-100
            backimage = UIImage(named: "chat_send_nor")
        }else{
            //接收者
            iconX = 10
            icon?.image = UIImage(named: "other")
            backimage = UIImage(named: "chat_recive_press_pic")
            textX = 70
        }

        icon?.frame = CGRect(x: iconX, y: 30, width: 50, height: 50)

        //3.設置正文,設置button顯示
        textmsg?.setTitle(msg.text, forState: UIControlState.Normal)
        textmsg?.frame = CGRect(x: textX, y: 30, width: size.width+30, height: size.height+30)
        textmsg?.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
        textmsg?.titleLabel?.numberOfLines=0
        textmsg?.contentEdgeInsets = UIEdgeInsetsMake(15,15, 15, 15);

        let inset = UIEdgeInsets(top: (backimage?.size.height)!*0.5 , left: (backimage?.size.width)!*0.5, bottom: (backimage?.size.height)!*0.5, right: (backimage?.size.width)!*0.5)

        let newimage =  backimage?.resizableImageWithCapInsets(inset)

        textmsg?.setBackgroundImage(newimage, forState: UIControlState.Normal)
    }

這裏關鍵是文字寬高的計算,和文字背景圖片拉伸計算、(這裏最好不要用label來顯示正文,因爲label要設置背景圖片的話,會比較麻煩,所以這邊是用button來做的、)

關鍵代碼:

 let size = NSString(string: msg.text).boundingRectWithSize(
 CGSizeMake(screenWdith!-140, CGFloat(MAXFLOAT)), 
 options: NSStringDrawingOptions.UsesLineFragmentOrigin ,
 attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(14)], 
 context: nil
 ).size

首先,String對象是沒有這個方法,先轉成NSString,調用boundingRectWithSize,第一個參數是文字所能接受的最大寬高,類型是CGSize,這邊的意思是寬度最大是 屏幕寬度-140 (爲何減去140? 這裏頭像算50 ,然後間隙 都是 10 ,兩邊頭像加間隙 10+50+10 +10+50+10),高度最大表示換行、第二個參數是繪製屬性(不清楚),第三個是字體屬性,這裏可以傳字體大小,字體類型等等

let inset = UIEdgeInsets(top: (backimage?.size.height)!*0.5 , left: (backimage?.size.width)!*0.5, bottom: (backimage?.size.height)!*0.5, right: (backimage?.size.width)!*0.5)

let newimage =  backimage?.resizableImageWithCapInsets(inset)

這裏做圖片拉伸,表示的是隻有中間拉伸,四周不變~(和.9圖片一個意思)

好的,這裏自定義cell基本完了

3.計算行高

即文字高度和頭像高度中的最大值
在tableview中寫代理方法

 override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        var rowheight :CGFloat = 0
        let msg = array[indexPath.row]

        //計算文字寬高!
        let size = NSString(string: msg.text).boundingRectWithSize(CGSizeMake(screenWdith!-140, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin , attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(14)], context: nil).size

        //4.計算總高!
        if size.height > 20{
            // 字的高度
            rowheight = size.height+70
        }else{
            //圖片的高度
            rowheight = 90
        }
        return rowheight
    }

4.重用cell

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //這裏做自定義cell重用
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")

        if cell == nil {
            cell = MsgCodeCell(style: UITableViewCellStyle.Default , reuseIdentifier: "cell")
            cell!.selectionStyle = UITableViewCellSelectionStyle.None
            NSLog("初始化cell")
        }

       (cell as! MsgCodeCell).setMsgModle(array[indexPath.row])
        return cell!
    }

至此,cell是做完了·

原文

————————————————
版權聲明:本文爲CSDN博主「行雲1992」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/xingyun1992/article/details/51172048

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章