Reputation: 4339
I have some problems with swift. Need to make tableview and in every cell to have image with text inside.
This is what i made so far:
Label should be auto height, now it breaks string..
Second problem:
Image needs to be auto height too, and to depends on label height.
Third problem:
Row needs to be autoheight depending on its inside.
TableViewController code:
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 44.0;
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.registerNib(UINib(nibName: "QuoteTableViewCell", bundle: nil), forCellReuseIdentifier: "QuoteCell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("QuoteCell", forIndexPath: indexPath) as! QuoteTableViewCell
cell.item = results[indexPath.row]
return cell
}
Cell code:
class QuoteTableViewCell: UITableViewCell {
var item: Quote! {
didSet {
setupCell()
}
}
@IBOutlet weak var imageField: UIView!
@IBOutlet weak var textField: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setupCell() {
self.imageField.backgroundColor = UIColor(patternImage: UIImage(named: "Bg")!)
textField.text = item.text
}
}
Upvotes: 1
Views: 1603
Reputation: 923
To have the label adapt its height to its contents, set its Lines number to 0 in Storyboard.
If you want to have an image next to it, why not to put both controls into one horizontal StackView?
And to have the tableView row height adapt to the cell contents (i.e. label height), just set it's rowHeight to automatic:
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 90.0;
Upvotes: 1
Reputation: 1126
Use this metod to have that functionality
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let lineBrakingMode = NSLineBreakMode.ByCharWrapping
let paragragh:NSMutableParagraphStyle = NSMutableParagraphStyle()
paragragh.lineBreakMode = lineBrakingMode
let attributes:NSDictionary = [NSFontAttributeName: self.textField.font!, NSParagraphStyleAttributeName:paragragh]
let TextSize = self.textField.text!.sizeWithAttributes(attributes)
let TextHeight = TextSize.height + 5;
UIView.animateKeyframesWithDuration(0.2, delay: 2.0, options: UIViewKeyframeAnimationOptions.AllowUserInteraction, animations: { () -> Void in
self.imageField.frame.height = TextHeight
}, completion: nil)
return TextHeight
}
}
Upvotes: 0