I'm having no luck getting an image and its UIImageView to show up the correct size in my custom UITableViewCell. The image is correct, but its place in the UITableViewCell is not, and isn't even close.
I don't have enough reputation points to post images sadly.
I have all the suggested constraints Xcode 6 added or suggested, but the image is showing up huge and in front of everything in my UITableViewCell.
Here's the only code I have related to it.
ViewController.m
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 600.0;
NSString *imageURL = [NSString stringWithFormat:#"%#", standardResolutionLocal.url];
__weak UITableViewCell *wcell = api2Cell;
[wcell.imageView
sd_setImageWithURL:[NSURL URLWithString:imageURL]
placeholderImage:[UIImage imageNamed:#"320x180.gif"]
];
CustomTableViewCell.m
- (void)layoutSubviews {
[super layoutSubviews];
[self.imageViewPic setTranslatesAutoresizingMaskIntoConstraints:YES];
}
I'm using iOS 8, Xcode 6, and SDWebImage via CocoaPods. Any help would be appreciated, thanks!
Select your image view and modify the Content Mode as desired - perhaps Aspect Fit will scale it appropriately. If it appears positioned correctly but continues to extend outside the image view bounds, enable Clips to Bounds.
Related
I have an app in which I have a side menu. In the side menu, the rest of the buttons appear fine but two buttons are stretching weirdly. screenshot attached.
This is how I am setting button images.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
RearViewTableViewCell *cell = [self.tableViewSideMenu dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(cell == nil)
{
NSArray *cellView = [[NSBundle mainBundle] loadNibNamed:#"RearViewTableViewCell" owner:nil options:nil];
cell = (RearViewTableViewCell *)[cellView objectAtIndex:0];
cell.btnItemSelector.tag = indexPath.row;
[cell.btnItemSelector setBackgroundImage:[UIImage imageNamed:[buttonUnselect objectAtIndex:indexPath.row]] forState:UIControlStateNormal];
[cell.btnItemSelector setBackgroundImage:[UIImage imageNamed:[buttonSelect objectAtIndex:indexPath.row]] forState:UIControlStateHighlighted];
[cell.btnItemSelector addTarget:self action:#selector(btnMenuItemTapped:) forControlEvents:UIControlEventTouchUpInside];
cell.selectionStyle =UITableViewCellSelectionStyleNone;
}
return cell;
}
I am new to adaptive layout. Is it causing issues? On iphone 5s it runs fine but on iphone 6 it is depicting this behaviour. I have added only one constraint (width) to the tableview. The uitableviewcell (custom) i am using here has all the regular constraints of leading space, vertical space, center alignment etc. Any thoughts?
Update: i set the bg color to red and it turns out the two buttons in questions are being resized to much smaller & probably wider view. Why would that happen?
I would recommend you, to use button.image instead of button.backgroundImage. It looks like setting a backgroundImage to a UIButton can't handle the contentMode of your image because it always stretches the UIImage to the same size as the UIButton.
If you add the UIImage just on the property image you can change position of the image inside the UIButton by changing the contentEdgeInsets manually or inside the Interface Builder.
Just in case you want to set an UIImage as well as a NSString for your UIButton, I would create an own class of type UIButton with an UILabel and UIImage and layout them inside the Interface Builder.
According to the "UIKit User Interface Catalog", "Buttons" chapter, "Images" section:
The Background (currentBackgroundImage) field allows you to specify an image to appear behind button content and fill the entire frame of the button. The image you specify will stretch to fill the button if it is too small. It will be cropped if it is too large.
Thus, you need to set size of all background images to be equal to button's size.
Update Or make sure that your constraints are configured so that button size is correct.
Alright guys I don't quite why this solved the problem but it did and here goes.
1) I used setImage rather than setBackgroundImage.
2) I removed the suffix .png from the images name.
3) I cleaned the project and reset the simulator.
4) It worked.
It was probably the cache still had previous images containing just ? and i symbol which made the button resize as per size of the image but I can't be sure. If anyone else can post a better explanation of this I'd mark it as Answer
This is really a n00b question, I am learning iOS while trying to build an app
I need to show an image, label on UITableViewCell. The following code does that for me
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.imageView.image = [self getImageNameForRow:indexPath.row];
cell.textLabel.text = self.features[(NSUInteger) indexPath.row];
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
return cell;
}
The problem is that image size comes bigger that I expect. so I tried to increase the height of row as
self.tableView.rowHeight = 80;
But then the image also scales up.
How can I keep my image size fixed while increasing (or changing) the size of the row?
The problem is that you are using a default table view cell style. That style comes with a built-in textLabel and an imageView, and the latter is a UIImageView with constraints so that it is resized to fill the height of the cell. But you have also said
cell.imageView.contentMode = UIViewContentModeScaleAspectFit
Which means that as the image view grows, the image grows with it - exactly what you are seeing.
The solution, as I explain here, is to size the image down to the actual size that you want it - and set the image view's contentMode to center. Something like this:
UIImage* im = [self getImageNameForRow:indexPath.row];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(36,36), YES, 0);
[im drawInRect:CGRectMake(0,0,36,36)];
UIImage* im2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = im2;
cell.imageView.contentMode = UIViewContentModeCenter;
Change that 36,36 to the size you actually want.
This is good practice anyway. It is a terrible waste of memory to hold onto an image at a larger size than needed for actual display (the amount of wasted memory grows exponentially, because area is on the order of the square of a single dimension). So you should always size images down to their actual display size. There's lots and lots of code on Stack Overflow showing many other ways to do that.
I believe your main problem here is the image is too large. If the image were only 40x40, it would appear as half the tableViewCell's height (when it's 80). IIRC the UIImageView in that UITableViewCell stretches to the height of the cell, and images will always fill it if they're large enough.
Three things you could do:
1) Shrink the size of the image to the size you want.
2) Change the frame of the imageView manually like so:
cell.imageView.image = [self getImageNameForRow:indexPath.row];
CGPoint center = cell.imageView.center;
CGRect frame = cell.imageView.frame;
frame.size.width = 40;
frame.size.height = 40;
cell.imageView.frame = frame;
cell.imageView.center = center;
I'm not entirely certain if you need to cache the center and re-set it after the frame change or not (the UITableViewCell might do this automatically).
3) Make a custom UITableViewCell subclass that has a fixed size UIImageView. I've detailed how to do this on my blog here.
I recommend 1 or 3.
Problem:
I use the following code inside the method cellForRowAtIndexPath to set the size of the image for the cell, yet at runtime the image gets blown up to the maximum height and width that the table row will allow.
UIImage *_image = [imageDictionary objectForKey:#"image"]; // Get image data
[_image drawInRect:CGRectMake(0,0,50,50)]; // set size
[cell.imageView setImage: _image]; // assign image to cell
cell.imageView.frame = CGRectMake(cell.imageView.frame.origin.x,cell.imageView.frame.origin.y,50,50);
return cell;
Question: Is there a more robust method of controlling the size of the image in a UITableViewCell? The approach I'm taking comes from several other posts but for some reason its being ignored in my code.
Side-note: I'm using Xcode 5 and developing on an iOS 7 platform.
Use UITableViewCell contentView .
The content view of a UITableViewCell object is the default superview for content displayed by the cell. If you want to customize cells by simply adding additional views, you should add them to the content view so they will be positioned appropriately as the cell transitions into and out of editing mode.
Example:
UIImage *_image = [imageDictionary objectForKey:#"image"]; // Get image data
[_image drawInRect:CGRectMake(0,0,50,50)]; // set size
UIImageView *imageView = [[UIImageView alloc] initWithImage: _image];
[imageView setFrame:yourFrame];
[cell.contentView addSubview:imageView];
This doesn't answer the question but your underlying problem is your approach. You should be customizing your cells by subclassing UITableViewCell. To add to that it's a lot easier to manipulate cell contents as views than to play around with the default picture and text label they give you. To carify, the contents of the cell sit on a view known as contentView accessible as cell.contentView. You can add text labels, buttons, and images as subviews to any location with any size you want the same way you would do with any view added as a subview.
I am loading in a list of facebook users using webcache and it works fantastically. Until you select one of the cells then it seems to either change the content mode, or more likely it changes the size of the uiimageview frame, but based on the actual size of the picture. for clarity here are some screens
here it is loaded
http://img.photobucket.com/albums/v246/homojedi/Screenshot20120727114807.png
and on selection of some of the images as you can see they seem to jump to their original aspect.
http://img.photobucket.com/albums/v246/homojedi/Screenshot20120727114827.png
as expected if i scroll them off screen and back to them they restore to what they were at the start.
It's baffling. The only thing i have not attempted is subclassing the uitableView and setting its layout subview there. short of that is there anything else i can do?
EDIT: code requested
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// typically you need know which item the user has selected.
// this method allows you to keep track of the selection
_indexPath = indexPath;
[_indexPath retain];
}
I've face exactly the same issue as you,and I fix
the issue is cause by you named your imageView "imageView"
i don't know why
if you change your imageView name like "m_imageView"
the issue fixed
It's all about naming!
I have come across this problem but I have no imageView property inside my custom UITableViewCell.
In fact I did make a stupid mistake by connecting an extra IBOutlet from my imageView object to the default imageView property of UITableViewCell. It is because I initially named my image view imageView, but then I changed it and forget about the outlet.
After removing the outlet, everything works fine.
Just in case someone else, like me, come upon this issue where non of the above worked.
I too had named my UIImageView: imageView. But, for some reason, even after renaming it, the problem persisted.
I tried everything I could think of, Reset Simulator, Clean Project, adding removing constrains....
As it turns out, simply deleting the UIImageView from the Storyboard and dragging a new one fixed it.
Couldn't have been a precompiled issue because I cleaned the project. Go figure.
I was having this issue and I solved it!!!
Check to make sure you synthesized the imageView property in your custom TableViewCell.
I forgot to synthesize a property (resulting in no getter/setter for the IBOutlet).
This topic is old but hope that helps someone else!
// reason for this problem is UITableView cell's imageview initially has a default size later on it resize it self on select so following cab be a solution for this: (Using AFNetworking to set image/ You can adjust accordingly)
__weak UItableViewCell *cellTemp = cell;
[cell.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]]
placeholderImage:[UIImage imageNamed:#"placeholder"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
cellTemp.imageView.image = image;
CGRect frameRect = cellTemp.imageView.frame;
frameRect.origin.y = (cellTemp.frame.size.height - image.size.height)/2;
frameRect.size.width = image.size.width;
frameRect.size.height = image.size.height;
cellTemp.imageView.frame = frameRect;
[cellTemp layoutSubviews];
// this will fit your cell's label
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
{
}];
I believe your problem is due to the UIImageView. You should be setting the image once - cell.imageView.image = myImage. Do not set a highlightedImage. Set the contentMode to maintain the aspect ratio of your image: cell.imageView.contentMode = UIViewContentModeScaleAspectFit;, and verify that the contentStretch rect is 0,0,1,1 (the default).
It is possible the tableView is changing the contentMode of the UIImageView or its frame when it gets selected (for who knows why reasons). I would add NSLogs to both willSelectRowAtIndexPath and didSelectRowAtIndexPath, showing the same information: the imageView frame, the contentMode value (as an integer), etc. Somehow one or more of these values is changing on selection.
Adding to the answers regarding the naming issue:
As it has been said, the problem with the image view persists even after renaming it. But it is not required to delete the UIImageView from your xib or storyboard. You can simply ctrl-click the image view and remove the connection to property imageView that still exists.
The reason the link to imageView still exists seems to be that the imageView property still remains available after you delete it in your code. It's still there because it is inherited from UITableViewCell.
One last hint that sounds stupid but took me a few minutes to realize: Obviously all code using property name imageView will still work but will result in strange behavior! So double check if there's no code left using the old property name.
I had the same issue, and even after trying all the previous answers none of them worked out. Later i found out that the UITableViewController had multiple unused Outlets, so deleting the unused Outlets fixed the problem.
As requested by sebastian-Luczak I did come up a solution for resizing, but now there is an image quality inconsistency, it gets higher resolution only when you touch it, strange but not as bad or noticable, anyway here is the code.
N.B i Am using SDWebImage to load the pictures asynchronously
[cell.imageView setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:#"Icon.png"]success:^(UIImage *image)
{
cell.imageView.image = [image resizeImage:image newSize:CGSizeMake(38, 38)];
} failure:^(NSError *error)
{
}];
// If you subclass UITableViewCell you can get rid of this problem
- (void)layoutSubviews {
[super layoutSubviews];
self.imageView.bounds = CGRectMake(10,5,65,65);
self.imageView.frame = CGRectMake(10,5,65,65);
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
}
I've created a cell prototype in the Xcode 4.2 storyboard that consists of an image view in the center of the cell and some text below it but when I run the app the image is always moved to the left side. I've made the cell extra tall to ensure it wasn't a height issue. I also played with the autosize settings.
So far nothing I've tried will make the image move to the center of the tableViewCell when the code is actually running.
Note, this is done purely in the StoryBoard. The only code I've written is code to create a list of objects with a "name" and "image" and the minimum table view source/delegate code so I can fill in two entries in the table.
I suppose you use something like :
static NSString *identifier = #"ImageRecordCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
UILabel *label = (UILabel*)[cell viewWithTag:1];
UIImageView *pic = (UIImageView*)[cell viewWithTag:2];
label.text = #"test";
pic.image = [UIImage imageNamed:#"Default.png"];
return cell;
be sure not to set tag to zero
I had something that works just fine in iOS 4.x, but was doing something similar to what you describe in the iOS 5 simulator, moving a UIImageView down by about 120px for no apparent reason. Setting the Autosizing settings to have the top position outside the box frozen (if that makes sense) fixed the issue—though it was not at all clear to me why this behavior had changed in iOS 5 vs. previously.