How do I resize the imageView?
Xcode says initialisation of imageView was never used.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let city = nicosiaPlaces [indexPath.row]
cell?.textLabel?.text = city
let imageView = CGSize(width: 100, height: 100)
cell?.imageView?.image = UIImage(named: city)
return cell!
}
You just create a new CGSize every time when the method is called, you should change the size in your cell class instead. And if you're using storyboard with AutoLayout, you should change the size in storyboard.
I guess your question has some flaws inside.
Assuming that you need to resize an Imageview I'm posting small Snippet for you.
Never initialize any new component inside func tableView(cellForRowAt:IndexPath)
beacuse every time it is going to create a new Instance until they are properly disposed.
You have taken reference as let imageView = CGSize(--,--) but you are again calling the instance from Cell Method.
Don't do that.
override func awakeFromNib(){
let imageView = UIImageView(CGRectMake(0,0,150,150))
imageView.contentMode = .scaleAspectFill
contentView.addSubView(imageView)
}
Now In the Class method get reference of the ImageView and resize if you want.
overrride func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.deququeResuableCell(withIdentifier: "cellID",forIndexPath: indexPath) as! yourCustomCellClassName
cell.imageView?.image = UIImage(named: "yourImage")
// If you need to resize the Image make changes in Frame of Image or ContentMode of the Image.
return cell
}
Related
The table cell is running shorter than it is supposed to be. (I use different background colour which shows difference width) The setting of cell is custom (only row height is change to 140). The playerCell class has nothing but some IBoutlets. Thanks.
(image: storyboard
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count: Int
if playerBank.count == 0
{
count = 1
}
else{
count = playerBank.count
}
return count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! playerCell
if playerBank.isEmpty{
let p = Player()
playerBank = setInvalidPlayer(pBank: p, userInput: userInputPlayerName)
}
let playerInBank: Player = playerBank[indexPath.row]
passImageUrl = cell.setPlayerCell(p: playerInBank)
urlBank.append(passImageUrl)
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
DispatchQueue.main.async {
self.performSegue(withIdentifier: "ShowPlayerInfo", sender: self)
}
}
My first guess is that, while you have a custom cell with custom outlets, that there are no layout constraints in place. So the items that you put into the storyboard are retaining their intrinsic values and not adapting to the device screen size.
If you add constraints to those outlets, especially enough to where the width of the cell can be determined based on the rest of the elements, then your cell should display full width.
I am new to swift, using swift 3, I built tableview that reads group of images and I want to have it as below:
when user select an image in the tableview I display it in an UIImageView and when Deselect an image he already selected in the tableview to be removed from the UIImageView ( Multiple Selection is enabled). My code below is working for one image selection only, however if multiple images are selected and then deselected the last selected one only removed from the UIImageview. So my question is how can I remove the UIImageview that belongs to the deselected record in the UItableview
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
image_view.image = UIImage(data: Saveddata[indexPath.row].photo as! Data)
//create image view programmatically
currentImageView = UIImageView(frame: CGRect(x: 130 + (i * 10), y: 50 + (i * 5), width: 50, height: 100))
currentImageView.contentMode = .scaleAspectFit
currentImageView.image = image_view.image
view.addSubview(currentImageView as UIView)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
currentImageView.removeFromSuperview()
}
You could use tag for each UIImageView based on the indexPath.row so you could refer by tag.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let image = UIImage(data: Saveddata[indexPath.row].photo as! Data)
//create image view programmatically
let imageView = UIImageView(frame: CGRect(x: 130 + (i * 10), y: 50 + (i * 5), width: 50, height: 100))
imageView.contentMode = .scaleAspectFit
imageView.tag = 100 + indexPath.row
imageView.image = image
view.addSubview(imageView as UIView)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
// get imageView by its tag
let deselectedImageView = view.viewWithTag(100 + indexPath.row) as! UIImageView
deselectedImageView.removeFromSuperview()
}
If you want to update your cell appearance when selected/deselected, you should override the method setSelected(_:animated:) inside your UITableViewCell subclass instead of trying to update it directly from your UITableViewDelegate method:
override func setSelected(_ selected: Bool, animated: Bool) {
// Do whatever you want depending on the selected value
}
So I have been stuck on this for a day or so. How do I change the color of an UIImage color when tapping on a tableview cell? So for example I have a black image and when I tap a tableview cell it changes that image to white? Thank you!
I tried using this code but I do not know how to implement it right!
let theImageView = UIImageView(image: UIImage(named:"foo")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))
theImageView.tintColor = UIColor.redColor()
It looks like you have the right pieces but don't know where to call them. You will assign the image to the image view in your cellForRowAt: method.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.imageView.image = UIImage(named:"foo")!.withRenderingMode(.alwaysTemplate)
return cell
}
Then you will change the tint color of the image view in the didSelect delegate method.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.imageView.tintColor = newColor
}
}
I want to dynamically change the height of the cell such that the image fills the imageView in the width and the image maintains the aspect ratio.
I am trying to do this using UITableViewAutomaticDimension. Based on tutorials available online, this seemed to be a straightforward task. But in my case, the height of the cell doesn't adjust to perform this task. Either the image fills with aspect ratio leaving a lot of width space empty or fills the width but clips the part of the image vertically. I made sure there are leading, trailing, top and bottom constraints with respect to the cell view and also the tableView.rowHeight = UITableViewAutomaticDimension and table.estimatedRowHeight is set in viewDidLoad. I have uploaded the project at this link. Could someone please suggest what could I be missing here?
Link to GitHub
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var picTableView: UITableView!
let reuseidentifier = "dynamicCellTableViewCell"
let images = [UIImage(named: "feedImage1"), UIImage(named: "feedImage2"), UIImage(named: "feedImage3")]
override func viewDidLoad() {
super.viewDidLoad()
picTableView.rowHeight = UITableViewAutomaticDimension
picTableView.estimatedRowHeight = 1000
}
// MARK: Table View Data Source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseidentifier, forIndexPath: indexPath) as! DynamicCellTableViewCell
cell.displayImageView.image = images[indexPath.row]
return cell
}
}
I figured the solution. UIImageView when used with UITableViewAutomaticDimension only looks for the UIImage's true width and height as the size. So UIImageView adjusts its height to respond to UIImage's original height and not the scaled height for scaled width (aspectFit) to match layout constraint.
So trick is to first change the width and height of the image to match the width and height that you need in the cell. Rest of the job will be done by UITableViewAutomaticDimension. Below is the updated cellForRowAtIndex function that works now. Thanks all for giving your inputs.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseidentifier, forIndexPath: indexPath) as! DynamicCellTableViewCell
let image = images[indexPath.row]!
let newWidth = cell.displayImageView.frame.width
let scale = newWidth/image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.displayImageView.image = newImage
return cell
}
You need implement next method for UITableViewController:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 1000.0;
}
Inside the method, you must know what dimension will have each cell. You must know in advance what height will have each cell.
For example, you could create an array of CGFloat saving the height will have each row, and when height change, you can update this position in array and execude tableView.reloadData().
var arrayHeight:CGFloat?
//Now fill array with height of each cell
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return arrayHeight[indexPath.row];
}
cell.updateConstraintsIfNeeded()
cell.setNeedsUpdateConstraints()
add these two lines in the cellForRowAtIndexPath delegate method
And make sure that top, bottom, right, left, constraints are set in the storyboard
The Table View Cells are laid out correctly during the initial load, but when I scroll up or down, the labels are shifted to the left. I'm not sure what is going on here.
My code for the tableview cell is below.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let workout = self.workouts[indexPath.row] as? Workout
let cell = tableView.dequeueReusableCellWithIdentifier("WorkoutCell") as? WorkOutCell
cell!.textCell?.text = workout?.title
cell!.backgroundColor = workout?.color
cell!.countLabel.text = "\(indexPath.row+1)"
cell!.selectionStyle = UITableViewCellSelectionStyle.None
return cell!
}
Image:
Thanks much!
Is there any changes if use this instead?
let cell = tableView.dequeueReusableCellWithIdentifier("WorkoutCell", forIndexPath: indexPath) as? WorkOutCell