我是iOS开发的新手.我的细胞大小有问题.我没有使用Auto-Laylout功能.我当前的TableView单元看起来像
like this.我想使
image中选择的标签大小根据该Label的文本内容动态扩展.
提前致谢.
解决方法
我认为像下面的快速版本,它计算更接近的值,而不是精确的高度,例如
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var messageArray:[String] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background","In case that app has been terminated while downloading was in progress,the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called,as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background."," If defined,this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.","Whale&W","Rcokey","Punch","See & Dive"] }
在上面我们有一个包含不同长度字符串的数组
func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return messageArray.count; } func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell; if(cell == nil) { cell = UITableViewCell(style:UITableViewCellStyle.default,reuseIdentifier: "CELL") cell?.selectionStyle = UITableViewCellSelectionStyle.none } cell?.textLabel.font = UIFont.systemFontOfSize(15.0) cell?.textLabel.sizeToFit() cell?.textLabel.text = messageArray[indexPath.row] cell?.textLabel.numberOfLines = 0 return cell!; } func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row]) return height + 70.0 } func calculateHeight(inString:String) -> CGFloat { let messageString = inString let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)] let attributedString : NSAttributedString = NSAttributedString(string: messageString,attributes: attributes) let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0,height: CGFloat.greatestFiniteMagnitude),options: .usesLineFragmentOrigin,context: nil) let requredSize:CGRect = rect return requredSize.height }
在新项目中尝试它只需添加tableview并设置其数据源并委托并通过上面的代码并运行
结果如下