IOS UITableViewCell 自定义高度动态调整 单元格 常用

//自定义单元格,单元格高度动态调整
1 import UIKit
2
3 class CustomizeUITableViewCell:UITableViewCell,
UITableViewDataSource, UITableViewDelegate {
4
5 var tableView:UITableView!;
6 var comments:[String] = []
7
8 override init(style:UITableViewCellStyle,
reuseIdentifier:String?) {
9
10 super.init(style:style, reuseIdentifier:
reuseIdentifier);
11
12 tableView = UITableView(frame:CGRect(x:20, y:0,
width:280, height:90))
13 tableView.dataSource = self
14 tableView.delegate = self
15 tableView.isScrollEnabled = false;
16
17 self.addSubview(tableView)
18 }
19
20 func tableView(_ tableView:UITableView,
numberOfRowsInSection section:Int) -> Int{
21 return comments.count
22 }
23
24 func tableView(_ tableView:UITableView,
cellForRowAt indexPath:IndexPath)
25 -> UITableViewCell {
26 let identifier = “reusedCell”
27 var cell =
tableView.dequeueReusableCell(withIdentifier:identifier)
28
29 if(cell == nil){
30 cell = UITableViewCell(style:
UITableViewCellStyle.default,
31 reuseIdentifier:identifier)
32 }
33 cell?.textLabel?.text = comments[(indexPath as
NSIndexPath).row]
34 cell?.textLabel?.font = UIFont.systemFont(ofSize:

35 cell?.textLabel?.textColor = UIColor.gray
36 cell?.textLabel?.numberOfLines = 0;
37 return cell!
38 }
39
40 func tableView(_ tableView:UITableView,
heightForRowAt indexPath:IndexPath)
41 -> CGFloat {
42 let subComments = comments[(indexPath as
NSIndexPath).row]
43 let size = subComments.boundingRect(with:CGSize(),
44 options:NSStringDrawingOptions.usesFontLeading,
attributes:nil, context:nil);
45 let cellHeight = size.heightsize.width/170
46 if(cellHeight < 30){
47 return 30
48 }else{
49 return cellHeight
50 }
51 }
52
53 func setCommentsForTable(_ comments:[String]){
54 self.comments = comments
55
56 var tableHeight:CGFloat = 0
57 for i in 0 ..< comments.count
58 {
59 let size = comments[i].boundingRect(with:CGSize(),
60 options:NSStringDrawingOptions.usesFontLeading,
attributes:nil, context:nil);
61 tableHeight += size.height
size.width/170
62 }
63 tableView.frame = CGRect(x:20, y:0, width:280,
height:tableHeight + 50)
64 tableView.reloadData()
65 }
66
67 func getMyHeight()->CGFloat{
68 return tableView.frame.size.height
69 }
70
71 required init(coder aDecoder:NSCoder) {
72 fatalError(“init(code:)has not brrn implomented”);
73 }
74 }

猜你喜欢

转载自blog.csdn.net/weixin_34320724/article/details/90866454
0条评论
添加一条新回复