Dynamic Cell Height Size Doesn't Work - ios

I am using swift 2.0 and trying to create table view without custom cell prototype. I wrote this:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor(patternImage: UIImage(named: "ViewBg.png")!)
self.tableView.estimatedRowHeight = 100.0
self.tableView.rowHeight = UITableViewAutomaticDimension
Alamofire.request(.GET, "https://****.herokuapp.com/user/000", parameters: nil)
.responseJSON { response in
let fortuneHistoryJson = JSON(response.result.value!)["fortuneHistory"]
for var index = 0; index < fortuneHistoryJson.count; ++index {
let FortuneHistoryItem = FortuneHistory()
FortuneHistoryItem.content = fortuneHistoryJson[index]["fortune"]["content"].string
FortuneHistoryItem.date = fortuneHistoryJson[index]["createdAt"].string
FortuneHistoryItem.imageUrl = fortuneHistoryJson[index]["cupPicture"].string
self.fortuneHistoryData.append(FortuneHistoryItem)
}
self.tableView.reloadData();
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fortuneHistoryData.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel!.text = self.fortuneHistoryData[indexPath.row].date;
cell.detailTextLabel!.text = self.fortuneHistoryData[indexPath.row].content
cell.textLabel!.numberOfLines = 0
cell.detailTextLabel!.numberOfLines = 0
cell.imageView!.kf_setImageWithURL(NSURL(string: self.fortuneHistoryData[indexPath.row].imageUrl )!, placeholderImage: UIImage(named: "ViewBg.png")!)
var itemSize: CGSize = CGSizeMake(100, 100)
UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.mainScreen().scale)
var imageRect: CGRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height)
cell.imageView!.image!.drawInRect(imageRect)
cell.imageView!.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return cell
}
I am expecting to enlarge cells by detailTextLabel size but they remains same and they are overlaps: http://i61.tinypic.com/1shb3b.jpg

I can't found any solution except creating custom cell prototype as #jrc mentioned. So solution is creating custom cell prototypes and using auto layout.

Related

Disable bounce effect on swipe to delete UITableViewCell in UITableView

I am implementing a swipe to delete feature on all UITableViewCell in my UITableView. In the same time I would like use a custom button, and for this purpose, this tutorial came in handy: Custom edit view in UITableViewCell while swipe left. Objective-C or Swift
(I went with the 4th solution). So far, I am satisfied with my overall result as it work out just well. However, I have noticed that in my case, when swiping on the cell, the cell travel does not stop just after the hidden button is unveiled, rather is continues and it unveils some gray space. Once the cell is released, it bounces back, covering the gray space. The big question is, how do I disable this bounce effect and have the cell stop on slide just after the button is unveiled?
My problem is very similar to this one How to remove UITableViewCell swipe to delete bounce
. However, I've tried all UISwipeViewDelegate solutions and none of them work for me.
What I need it to be like:
What it's actually like:
This is my code:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
lazy var rowHeight: CGFloat = {
return 82
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
let nibName = UINib(nibName: "TableViewCell", bundle: nil)
tableView.register(nibName, forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.makeCellWith(image: "sampleImage", userName: "userNameSample")
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return rowHeight
}
// MARK: - Cell Sections
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.frame = UIEdgeInsetsInsetRect(view.frame, UIEdgeInsetsMake(0, 10, 0, 10))
}
// Set the spacing between sections
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
// Make the background color show through
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.clear
return headerView
}
// MARK: - Slide to delete feature
fileprivate func whitespaceString(font: UIFont = UIFont.systemFont(ofSize: 15), width: CGFloat) -> String {
let padding: CGFloat = 20
let mutable = NSMutableString(string: "")
let attribute = [NSAttributedStringKey.font: font]
while mutable.size(withAttributes: attribute).width < width - (2 * padding) {
mutable.append(" ")
}
return mutable as String
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let whitespace = whitespaceString(width: rowHeight)
let deleteAction = UITableViewRowAction(style: .default, title: whitespace) { (action, indexPath) in
// do action on delete here
}
// create a color from pattern image and set the color as a background color of action
let view = UIView(frame: CGRect(x: 0, y: 0, width: rowHeight, height: rowHeight))
view.backgroundColor = UIColor.white
let imageSize: CGFloat = 50
let imageView: UIImageView = {
let iv = UIImageView()
let buttonImage = UIImage(named: "plusButton")
iv.image = buttonImage
return iv
}()
imageView.frame = CGRect(x: (view.frame.height - imageSize)/2,
y: (view.frame.width - imageSize)/2,
width: imageSize,
height: imageSize)
view.addSubview(imageView)
let image = view.image()
deleteAction.backgroundColor = UIColor(patternImage: image)
return [deleteAction]
}
// MARK: - Delete Object
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
fileprivate extension UIView {
func image() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
guard let context = UIGraphicsGetCurrentContext() else {
return UIImage()
}
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}

how to adjust uilabel and uitableviewcell height programmatically?

I know that adjusting UILabel height and UITableViewCell is probably a pretty standard issue, but I'm finding lots of answers that are based on the storyboard and inspectors, but not by just using Swift 3. I've created a table which covers the screen. The height for the cell is being determined as follows:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
My tableViewCell has a couple of objects in it, a UIImageView (myImage) and a UILabel (myText), set-up in a custom class. The positioning and sizing takes place in cellForRowAt.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.myImage.image = UIImage(named: "MyImage")
cell.myImage.layer.frame = CGRect(origin: CGPoint(x: 0, y: 10), size: (cell.myImage?.image?.size)!)
cell.myText.text = myArray[indexPath.row]
cell.myText.frame = CGRect(x: UIScreen.main.bounds.size.width * 0.25, y: 0, width: UIScreen.main.bounds.size.width * 0.7, height: 90)
cell.myText.numberOfLines = 0
return cell
}
The result is a bunch of stacked cells, overlapping each other. What should I do to adjust the height of the UILabel frame to the amount of text coming from myArray and adjust the cell height so that it's at least the height of myImage or myText?
You can make multiline label inside table view in Swift 3.
import UIKit
private let useAutosizingCells = true
class TableViewController: UITableViewController {
fileprivate let cellIdentifier = "Cell"
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//setup initial row height here
if useAutosizingCells && tableView.responds(to: #selector(getter: UIView.layoutMargins)) {
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
}
}
// MARK: - UITableViewDataSource
extension TableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return detailsModel.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
let details = detailsModel[indexPath.row]
cell.textLabel?.text = details.title
cell.detailTextLabel?.text = details.description
if useAutosizingCells && tableView.responds(to: #selector(getter: UIView.layoutMargins)) {
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.numberOfLines = 0
}
return cell
}
}

UITableViewCell style subtitle mutiple line not working

I have one custom style UITableviewCell and it have default height for other I am using tableview cell with style of subtitle and I want to make subtitle to be multiple lines. And it's doing good but having problem with calculating tableview cell height and I use UITableviewAutomaticDimension but its not working.
Here is my code
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if(indexPath.row==0){
var cell: ImageCell! = tableView.dequeueReusableCellWithIdentifier("ImageCell") as? ImageCell
if cell == nil {
tableView.registerNib(UINib(nibName: "ImageCell" ,bundle: nil), forCellReuseIdentifier: "ImageCell")
cell = tableView.dequeueReusableCellWithIdentifier("ImageCell") as? ImageCell
}
return cell
}else{
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("SubtitleCell")
if (cell == nil) {
cell = UITableViewCell.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "SubtitleCell")
cell!.backgroundColor = UIColor.brownColor()
cell!.textLabel?.font = UIFont.init(name: "HelveticaNeue", size: 15)
cell!.textLabel?.textColor = UIColor.blackColor()
cell!.textLabel?.highlightedTextColor = UIColor.lightGrayColor()
cell!.selectedBackgroundView = UIView.init()
}
cell!.textLabel?.text = "TExt"
cell!.detailTextLabel!.text="Keep in mind that UITableView is defined as an optional in the function, which means your initial cell declaration needs to check for the optional in the property. Also, the returned queued cell is also optional, so ensure you make an optional cast to UITableViewCell. Afterwards, we can force unwrap because we know we have a cell."
allowMultipleLines(cell!)
cell!.imageView?.image = UIImage(named: "IconProfile")
return cell!
}
}
func allowMultipleLines(tableViewCell:UITableViewCell) {
tableViewCell.detailTextLabel?.numberOfLines = 0
tableViewCell.detailTextLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(indexPath.row==0){
return 172
}else{
return UITableViewAutomaticDimension
}
}
in your viewDidLoad() Method you need to write
yourTableViewName.rowHeight = UITableViewAutomaticDimension
And Add One more method
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(indexPath.row==0){
return 172
}else{
return UITableViewAutomaticDimension;
}
}
i hope this will help you

How to automatically resize rowheight in table in UITableViewController in swift 2?

i am trying to resize row height programmatically in table in UITableViewController. i tried this
class MyProfile: UITableViewController {
var details:[String] = ["collection","of","titles","are","written","here"]
var subdetails:[String] = ["it", "is","a" ,"big", "string", "list"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0
tableView.tableFooterView = UIView()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return details.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = "eachCellProfile"
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as UITableViewCell?
if (cell != nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
cell!.detailTextLabel?.font = UIFont.boldSystemFontOfSize(16.0)
cell?.detailTextLabel?.numberOfLines = 10
cell!.textLabel?.text = self.details[indexPath.row]
cell!.detailTextLabel?.text = self.subdetails[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
i didn't add any restriction in table cell. i want to set row height according to title and title details string's length and font size. how can i do it?
Use the heightForRowAtIndexPath to calculate height of each cell before it is created. Use the title detail string that you will use to find the height of and add it to a default height. In my case my default height of cell is 85 and font size is 15.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var returnValue = CGFloat()
if (dataArray.count > 0) {
let stringData = dataArray[indexPath.row] as NSString
let constraintRect = CGSize(width: 280.0, height: CGFloat.max)
//get height of the string used
let boundingBox = stringData.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)], context: nil)
return boundingBox.height + CGFloat(85.0)
}
else{
returnValue = CGFloat(85.0);
}
return returnValue;
}
This gave me dynamic cell height according to its content. Hope this helps

UITableView - I want to display blank cell

I set up my tableView and has two springVar as shown in the image below. I want my tableview to show empty cells after the two springVar so that my solve bar is at the bottom of the screen. Any advices on how to go about it? My code is below.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return springVar.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: cellIdentifier)
}
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
var data : NSManagedObject = springVar[indexPath.row] as! NSManagedObject
cell!.textLabel!.text = "Spring \(indexPath.row + 1)"
var force : Float = data.valueForKey("force") as! Float
var stiffness : Float = data.valueForKey("stiffness") as! Float
cell!.detailTextLabel!.text = "Force =\(force) \t Stiffness =\(stiffness)"
cell!.detailTextLabel!.textColor = UIColor .darkGrayColor()
return cell!
}
i think this maybe helpfull
if indexPAth.row / 2 == 0
{
return UITableViewCell()
// u can customize ur cell to show a button or anything else
}
this show a custom/blank cell after each 2 cell,(odd)
You can add Footer view in your tableView this way:
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
footerView.backgroundColor = UIColor.whiteColor()
//add button in your footer view
var button = UIButton(frame: CGRectMake(0, 0, 75, 30))
button.setTitle("Solve", forState: UIControlState.Normal)
button.setTitleColor(UIColor.brownColor(), forState: UIControlState.Normal)
button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
footerView.addSubview(button)
return footerView
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 40.0
}
And your result will be:
You can adjust the footerHeight according to your own needs.
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerHeight : CGFloat = (tableView.frame.size.height - (CGFloat(springVar.count) * 45.0) - 45.0 - 64.0)
let oneCell = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: footerHeight))
return oneCell
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let footerHeight : CGFloat = (tableView.frame.size.height - (CGFloat(springVar.count) * 45.0) - 45.0 - 64.0)
return footerHeight
}

Resources