Adjust UICollectionViewFlowLayout When UICollectionView Frame Changes - objective-c

I have a UICollectionView that I created programmatically, along with its UICollectionViewFlowLayout. The code for this looks like:
- (UICollectionView *)createCollectionToDisplayContent:(NSArray *)array ViewWithCellIdentifier:(NSString *)cellIdentifier ofWidth:(CGFloat)width withHeight:(CGFloat)height forEmailView:(EmailView *)emailView
{
CGFloat minInterItemSpacing;
if (!self.orientationIsLandscape) minInterItemSpacing = 9.0f;
else minInterItemSpacing = 20.0f;
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.itemSize = CGSizeMake(220.0f, 45.0f);
layout.sectionInset = UIEdgeInsetsMake(5.0f, 0.0f, 5.0f, 0.0f);
layout.minimumLineSpacing = 10.0f;
layout.minimumInteritemSpacing = minInterItemSpacing;
//get pointer to layout so I can change it later
emailView.personLabelsLayout = layout;
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(40, 4, width, height) collectionViewLayout:layout];
collectionView.dataSource = emailView;
collectionView.delegate = emailView;
collectionView.scrollEnabled = NO;
collectionView.userInteractionEnabled = YES;
collectionView.backgroundColor = [UIColor clearColor];
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
collectionView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin);
[collectionView reloadData];
return collectionView;
}
This code works fine to initially display the collection view. My issue is in trying to change the flow layout when the device is rotated. I handle the change in the collection view frame using struts and springs (see above), and in the willAnimateRotationToInterfaceOrientation method, I adjust the minimumInterItemSpacing property of the flow layout, and finally call reload data on the collection view. Here is the code for that:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
CGFloat minInterItemSpacing;
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
minInterItemSpacing = 20.0f;
} else {
minInterItemSpacing = 9.0f;
}
self.visibleEmailView = //...more code
self.visibleEmailView.personLabelsLayout.minimumInteritemSpacing = minInterItemSpacing;
[self.visibleEmailView.personLabelsCollectionView reloadData];
//other stuff...
}
Ultimately, the flow layout should adjust dramatically when the view is rotated: in terms of the minimumInterItemSpacing but also in terms of the number of columns it displays. However, the layout is not adjusting as I would expect. I am having trouble figuring out what exactly is even happening. It looks like the minimumInterItemSpacing is not being reset on rotation, and it looks like for each cell, the same cell is being drawn over itself multiple times. Also, I'm getting crashes that say:
"the collection view's data source did not return a valid cell from -collectionView:cellForItemAtIndexPath: for index path <NSIndexPath 0x9be47e0> 2 indexes [0, 6]"
In trying to begin to narrow down what is going on here, I am wondering if anyone can tell me if my approach is correct, and/or if there is an obvious error in my code that might be causing some or all of this funky behavior.

Are you implementing anything like this?
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
]

Related

While using ECSlidingViewController, why doesn't the underRightViewController animate correctly?

I am trying to implement ECSlidingViewController to perform a Zoom effect. While using underLeftViewController and anchorTopViewToRightAnimated, the effect is flawless and exceptional. However, I need to use underRightViewController and anchorTopViewToLeftAnimated in specific cases. When I do so, however, the same View Controller that worked flawlessly on the left acts unpredictable on the right. The views end up in basically the right places, but they do not animate at all. Here's my code for creating and setting up the ECSlidingViewController:
if (self.slidingViewController == nil)
{
self.fieldSearchController = [[FieldSearchTableViewController alloc] initWithNibName:#"FieldSearchTableViewController" bundle:nil];
self.filterVC = [[FieldSearchFilterTableViewController alloc] initWithNibName:#"FieldSearchFilterTableViewController" bundle:nil];
self.slidingViewController = [[ECSlidingViewController alloc] initWithTopViewController:self.fieldSearchController];
//self.slidingViewController.underLeftViewController = self.filterVC;
self.slidingViewController.underRightViewController = self.filterVC;
}
if (self.slidingViewController.parentViewController == nil)
{
[self addChildViewController:self.slidingViewController];
CGRect frame = self.view.bounds;
NSInteger topSize = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
frame.origin.y = topSize;
frame.size.height -= topSize;
self.slidingViewController.view.frame = frame;
[self.view addSubview:self.slidingViewController.view];
}
And here's the main code I am using for the top view:
//0 - Default
//1 - Fold
//2 - Zoom
//3 - Dynamic
NSDictionary *transitionData = self.transitions.all[0];
id<ECSlidingViewControllerDelegate> transition = transitionData[#"transition"];
if (transition == (id)[NSNull null]) {
super.slidingViewController.delegate = nil;
} else {
self.slidingViewController.delegate = transition;
}
NSString *transitionName = transitionData[#"name"];
if ([transitionName isEqualToString:METransitionNameDynamic]) {
self.slidingViewController.topViewAnchoredGesture = ECSlidingViewControllerAnchoredGestureTapping | ECSlidingViewControllerAnchoredGestureCustom;
self.slidingViewController.customAnchoredGestures = #[self.dynamicTransitionPanGesture];
[self.navigationController.view removeGestureRecognizer:self.slidingViewController.panGesture];
[self.navigationController.view addGestureRecognizer:self.dynamicTransitionPanGesture];
} else {
self.slidingViewController.topViewAnchoredGesture = ECSlidingViewControllerAnchoredGestureTapping | ECSlidingViewControllerAnchoredGesturePanning;
self.slidingViewController.customAnchoredGestures = #[];
[self.navigationController.view removeGestureRecognizer:self.dynamicTransitionPanGesture];
[self.navigationController.view addGestureRecognizer:self.slidingViewController.panGesture];
}
[self.slidingViewController anchorTopViewToLeftAnimated:YES];
This is not all of the code, but I think the problem is somewhere in one of these two blocks. Or maybe, the animate to the right just doesn't work like I think it should? I haven't seen any other examples using this approach so I might need to do some more customizations to the control, IDK.
Thanks for any help offered on this.
Short answer: you need to resetTopViewController first.
See: ECSlidingViewController 2 sliding from right to left

UITableViewCell content overlaps delete button when in editing mode in iOS7

I am creating a UITableView with custom UITableViewCells. iOS 7's new delete button is causing some problems with the layout of my cell.
If I use the "Edit" button, which makes the red circles appear I get the problem, but if I swipe a single cell it looks perfect.
This is when the Edit button is used:
[self.tableView setEditing:!self.tableView.editing animated:YES];
This is when I swipe a single cell:
As you can se my labels overlaps the delete button in the first example. Why does it do this and how can I fix it?
try using the accessoryView and editingAccessoryView properties of your UITableViewCell, instead of adding the view yourself.
If you want the same indicator displayed in both editing and none-editing mode, try setting both view properties to point at the same view in your uiTableViewCell like:
self.accessoryView = self.imgPushEnabled;
self.editingAccessoryView = self.imgPushEnabled;
There seems to be a glitch in the table editing animation in IOS7, giving an overlap of the delete button and the accessoryView when switching back to non-editing state. This seems to happen when the accesoryView is specified and the editingAccessoryView is nil.
A workaround for this glitch, seems to be specifying an invisible editingAccessoryView like:
self.editingAccessoryView =[[UIView alloc] init];
self.editingAccessoryView.backgroundColor = [UIColor clearColor];
The problem is that in edit mode the cell's contentView changes in size. So either you have to override layoutSubviews in your cell and support the different frame sizes
- (void) layoutSubviews
{
[super layoutSubviews];
CGRect contentFrame = self.contentView.frame;
// adjust to the contentView frame
...
}
or you take the bait and switch to autolayout.
First I thought setting contentView.clipsToBounds to YES could be an ugly workaround but that does not seem to work.
I've resolved this problem with set up constraints without width only leading and trailing
As tcurdt mentioned, you could switch to autolayout to solve this issue. But, if you (understandably) don't want to mess with autolayout just for this one instance, you can set the autoresizingMask and have that turned automatically into the appropriate autolayout constraints.
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
Just use this method in your custom TableViewCell class you can get the perfect answer,
Here self is UITableviewCell
- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subview in self.subviews) {
for (UIView *subview2 in subview.subviews) {
if ([NSStringFromClass([subview2 class]) isEqualToString:#"UITableViewCellDeleteConfirmationView"]) { // move delete confirmation view
[subview bringSubviewToFront:subview2];
}
}
}
}
And if any one want to adjust the Delete Button Size, Use the following Code
- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subview in self.subviews) {
for (UIView *subview2 in subview.subviews) {
if ([NSStringFromClass([subview2 class]) isEqualToString:#"UITableViewCellDeleteConfirmationView"]) { // move delete confirmation view
CGRect rect = subview2.frame;
rect.size.height = 47; //adjusting the view height
subview2.frame = rect;
for (UIButton *btn in [subview2 subviews]) {
if ([NSStringFromClass([btn class]) isEqualToString:#"UITableViewCellDeleteConfirmationButton"]) { // adjusting the Button height
rect = btn.frame;
rect.size.height = CGRectGetHeight(subview2.frame);
btn.frame = rect;
break;
}
}
[subview bringSubviewToFront:subview2];
}
}
}
}
Best way to remove this problem is that add an image in cell and set it in Backside.
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"bgImg.png"]];
imageView.frame = CGRectMake(0, 0, 320, yourCustomCell.frame.size.height);
[yourCustomCell addSubview:imageView];
[yourCustomCell sendSubviewToBack:imageView];
If your text would overlap the delete button then implement Autolayout. It'll manage it in better way.
One more case can be generate that is cellSelectionStyle would highlight with default color. You can set highlight color as follows
yourCustomCell.selectionStyle = UITableViewCellSelectionStyleNone;
Set your table cell's selection style to UITableViewCellSelectionStyleNone. This will remove the blue background highlighting or other. Then, to make the text label or contentview highlighting work the way you want, use this method in yourCustomCell.m class.
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
if (highlighted)
self.contentView.backgroundColor = [UIColor greenColor];
else
self.contentView.backgroundColor = [UIColor clearColor];
}
I hope you understand it in a better way.
Bringing to front UITableViewCellDeleteConfirmationView in the layoutSubviews of the custom cell works for me on iPhone, but not on iPad.
I have a UITableView in the master part of a splitViewController for the iPad, and in this case
the frame of the UITableViewCellDeleteConfirmationView is (768 0; 89 44), instead of (320 0; 89 44)
So I resize the frame in the layoutSubviews method and this works for me
- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subview in self.subviews)
{
for (UIView *subview2 in subview.subviews)
{
if ([NSStringFromClass([subview2 class]) isEqualToString:#"UITableViewCellDeleteConfirmationView"])
{
CGRect frame = subview2.frame;
frame.origin.x = 320;
subview2.frame = frame;
[subview bringSubviewToFront:subview2];
}
}
}
}
If you are putting content in the UITableViewCell's contentView, be sure you use self.contentView.frame.size.width and not self.frame.size.width in layoutSubviews.
self.frame expands width in editing mode, and will cause any content on the right to extend past the bounds of the contentView. self.contentView.frame stays at the correct width (and is what you should be using).
Try this: Might be you are setting cell setBackgroundImage in cellForRowAtIndexPath (Delegate Method). Do not set this here. Set your image in:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"cellList.png"]]; }
Enjoy Coding.
My solution is to move whole contentView to the left when Delete button showing:
override func layoutSubviews() {
super.layoutSubviews()
if editingStyle == UITableViewCellEditingStyle.Delete {
var rect = contentView.frame
rect.origin.x = self.showingDeleteConfirmation ? -15 : 38
contentView.frame = rect
}
}

hide UITableView header section

I'm using the following code to hide a view and the space taken by the view based on a condition in viewWillAppear:
- (void)viewWillAppear:(BOOL)animated {
Data* data = [Data shared];
if (data.something == 0) {
CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = 0;
self.tableView.tableHeaderView.frame = frame;
self.tableView.tableHeaderView.hidden = YES;
} else {
CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = 44;
self.tableView.tableHeaderView.frame = frame;
self.tableView.tableHeaderView.hidden = NO;
}
}
The above code works, but I'm pretty sure that is not the right way to do that. I tried to set the tableHeaderView to nil, but once the code is called, the headerView is gone until the UITableView is destroyed (I think I can fix it using a IBOutlet to the tableHeader, but doesn't sounds right too.
UPDATE1: another try, but the code doesn't work:
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section {
self.tableView.tableHeaderView.hidden = YES;
return 0;
}
The data source method tableView:heightForHeaderInSection: actually has nothing to do with the view that is associated with the table view's tableViewHeader property. There are two different types of headers here, the one header at the top of the tableView, in which can be placed things like a search bar, and the multiple headers that can be made to occur one per section within the table view.
To my knowledge, the tableViewHeader view is typically configured in the nib file, and I don't know that the table view calls any data source methods that allow any configuration for it, so you would have to do it manually. Frankly, if your code works, that would be a good way to do it. Hiding it would make the table view still act as if it's there...removing it entirely makes it so you can't get it back because it gets deallocated.
(However, as you said, you could use an IBOutlet pointing to the header view, as long as you make it a strong reference, and then you could somehow reinsert it into the table later. ...Hm, although the mechanics of how you add a view into the table view's scroll view, and position it correctly, is probably just annoying.)
My only suggestion would be animating the frame height to zero so you get a nice transition effect, something like animateWithDuration. But yeah, I would say you have the best method figured out already.
EDIT:
Code, you say? I take that as a challenge :)
- (void)setTableViewHeaderHidden:(BOOL)hide
{
// Don't want to muck things up if we are mid an animation.
if (self.isAnimatingHeader) {
return;
}
// This is our IBOutlet property, I am just saving a bit of typing.
UIView *theHeader = self.theHeaderView;
if (hide) {
// Save the original height into the tag, should only be done once.
if (!theHeader.tag) {
theHeader.tag = theHeader.frame.size.height;
}
// Transform and hide
if (theHeader.frame.size.height > 0) {
self.isAnimatingHeader = YES;
// New frame...
CGRect frame = theHeader.frame;
frame.size.height = 0;
// Figure out some offsets here so we prevent jumping...
CGPoint originalOffset = self.tableView.contentOffset;
CGPoint animOffset = originalOffset;
animOffset.y += MAX(0, theHeader.tag - animOffset.y);
CGPoint newOffset = originalOffset;
newOffset.y = MAX(0, newOffset.y - theHeader.tag);
// Perform the animation
[UIView animateWithDuration:0.35
delay:0.0
options: UIViewAnimationCurveEaseOut
animations:^{
theHeader.frame = frame;
self.tableView.contentOffset = animOffset;
}
completion:^(BOOL finished){
if (finished) {
// Hide the header
self.tableView.tableHeaderView = nil;
theHeader.hidden = YES;
// Shift the content offset so we don't get a jump
self.tableView.contentOffset = newOffset;
// Done animating.
self.isAnimatingHeader = NO;
}
}
];
}
} else {
// Show and transform
if (theHeader.frame.size.height < theHeader.tag) {
self.isAnimatingHeader = YES;
// Set the frame to the original before we transform, so that the tableview corrects the cell positions when we re-add it.
CGRect originalFrame = theHeader.frame;
originalFrame.size.height = theHeader.tag;
theHeader.frame = originalFrame;
// Show before we transform so that you can see it happen
self.tableView.tableHeaderView = theHeader;
theHeader.hidden = NO;
// Figure out some offsets so we don't get the table jumping...
CGPoint originalOffset = self.tableView.contentOffset;
CGPoint startOffset = originalOffset;
startOffset.y += theHeader.tag;
self.tableView.contentOffset = startOffset; // Correct for the view insertion right off the bat
// Now, I don't know if you want the top header to animate in or not. If you think about it, you only *need* to animate the header *out* because the user might be looking at it. I figure only animate it in if the user is already scrolled to the top, but hey, this is open to customization and personal preference.
if (self.animateInTopHeader && originalOffset.y == 0) {
CGPoint animOffset = originalOffset;
// Perform the animation
[UIView animateWithDuration:0.35
delay:0.0
options: UIViewAnimationCurveEaseIn
animations:^{
self.tableView.contentOffset = animOffset;
}
completion:^(BOOL finished){
// Done animating.
self.isAnimatingHeader = NO;
}
];
} else {
self.isAnimatingHeader = NO;
}
}
}
}
Built this in the table view template that comes with Xcode. Just to throw it together I used a UILongPressGestureRecognizer with the selector outlet pointing to this method:
- (IBAction)longPress:(UIGestureRecognizer *)sender
{
if (sender.state != UIGestureRecognizerStateBegan) {
return;
}
if (self.hidingHeader) {
self.hidingHeader = NO;
[self setTableViewHeaderHidden:NO];
} else {
self.hidingHeader = YES;
[self setTableViewHeaderHidden:YES];
}
}
And, I added these to my header:
#property (strong, nonatomic) IBOutlet UIView *theHeaderView;
#property (nonatomic) BOOL hidingHeader;
#property (nonatomic) BOOL isAnimatingHeader;
#property (nonatomic) BOOL animateInTopHeader;
- (IBAction)longPress:(id)sender;
Anyway, it works great. What I did discover is that you definitely have to nil out the table view's reference to the header view or it doesn't go away, and the table view will shift the cells' position based on the height of the frame of the header when it is assigned back into its header property. Additionally, you do have to maintain a strong reference via your IBOutlet to the header or it gets thrown away when you nil out the table view's reference to it.
Cheers.
Instead of,
if (1 == 1) {
CGRect frame = self.viewHeader.frame;
frame.size.height = 0;
self.viewHeader.frame = frame;
self.viewHeader.hidden = YES;
}
use it as,
if (1 == 1) {
self.viewHeader.hidden = YES;
}
If you do not want the view anymore instead of just hiding, use [self.viewHeader removeFromSuperview];
And if you want to add it after removing [self.view addSubview:self.viewHeader]; All these depends on your requirement.
Update:
for eg:-
if (data.something == 0) {
//set frame1 as frame without tableHeaderView
self.tableView.frame = frame1;
self.tableView.tableHeaderView.hidden = YES;
} else {
//set frame2 as frame with tableHeaderView
self.tableView.frame = frame2;
self.tableView.tableHeaderView.hidden = NO;
}
or,
if (data.something == 0) {
//set frame1 as frame without tableHeaderView
self.tableView.frame = frame1;
self.tableView.tableHeaderView = nil;
} else {
//set frame2 as frame with tableHeaderView
self.tableView.frame = frame2;
self.tableView.tableHeaderView = self.headerView; //assuming that self.headerview is the tableHeaderView created while creating the tableview
}
Update2: Here is a very simple version of animation block.
if (data.something == 0) {
[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationCurveEaseOut
animations:^{
//set frame1 as frame without tableHeaderView
self.tableView.frame = frame1;
self.tableView.tableHeaderView.hidden = YES; // or self.tableView.tableHeaderView = nil;
}
completion:^(BOOL finished){
//if required keep self.tableView.frame = frame1;
}
];
} else {
[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationCurveEaseIn
animations:^{
//set frame2 as frame with tableHeaderView
self.tableView.frame = frame2;
self.tableView.tableHeaderView.hidden = NO;// or self.tableView.tableHeaderView = self.headerView;
}
completion:^(BOOL finished){
//if required keep self.tableView.frame = frame2;
}];
}

Why do all backgrounds disappear on UITableViewCell select?

My current project's UITableViewCell behavior is baffling me. I have a fairly straightforward subclass of UITableViewCell. It adds a few extra elements to the base view (via [self.contentView addSubview:...] and sets background colors on the elements to have them look like black and grey rectangular boxes.
Because the background of the entire table has this concrete-like texture image, each cell's background needs to be transparent, even when selected, but in that case it should darken a bit. I've set a custom semi-transparent selected background to achieve this effect:
UIView *background = [[[UIView alloc] initWithFrame:self.bounds] autorelease];
background.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
background.opaque = NO;
[self setSelectedBackgroundView:background];
And although that yields the right look for the background, a weird side effect happens when I select the cell; all other backgrounds are somehow turnt off. Here's a screenshot. The bottom cell looks like it should and is not selected. The top cell is selected, but it should display the black and grey rectangular areas, yet they are gone!
Who knows what's going on here and even more important: how can I correct this?
What is happening is that each subview inside the TableViewCell will receive the setSelected and setHighlighted methods. The setSelected method will remove background colors but if you set it for the selected state it will be corrected.
For example if those are UILabels added as subviews in your customized cell, then you can add this to the setSelected method of your TableViewCell implementation code:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
self.textLabel.backgroundColor = [UIColor blackColor];
}
where self.textLabel would be whatever those labels are that are shown in the picture above
I'm not sure where your adding your selected view, I usually add it in the setSelected method.
Alternatively, you can subclass the UILabel and override the setHighlighted method like so:
-(void)setHighlighted:(BOOL)highlighted
{
[self setBackgroundColor:[UIColor blackColor]];
}
The cell highlighting process can seem complex and confusing if you don't know whats going on. I was thoroughly confused and did some extensive experimentation. Here's the notes on my findings that may help somebody (if anyone has anything to add to this or refute then please comment and I will endeavour to confirm and update)
In the normal “not selected” state
The contentView (whats in your XIB unless you coded it otherwise) is drawn normally
The selectedBackgroundView is HIDDEN
The backgroundView is visible (so provided your contentView is transparent you see the backgroundView or (if you have not defined a backgroundView you'll see the background colour of the UITableView itself)
A cell is selected, the following occurs immediately with-OUT any animation:
All views/subviews within the contentView have their backgroundColor cleared (or set to transparent), label etc text color's change to their selected colour
The selectedBackgroundView becomes visible (this view is always the full size of the cell (a custom frame is ignored, use a subview if you need to). Also note the backgroundColor of subViews are not displayed for some reason, perhaps they're set transparent like the contentView). If you didn't define a selectedBackgroundView then Cocoa will create/insert the blue (or gray) gradient background and display this for you)
The backgroundView is unchanged
When the cell is deselected, an animation to remove the highlighting starts:
The selectedBackgroundView alpha property is animated from 1.0 (fully opaque) to 0.0 (fully transparent).
The backgroundView is again unchanged (so the animation looks like a crossfade between selectedBackgroundView and backgroundView)
ONLY ONCE the animation has finished does the contentView get redrawn in the "not-selected" state and its subview backgroundColor's become visible again (this can cause your animation to look horrible so it is advisable that you don't use UIView.backgroundColor in your contentView)
CONCLUSIONS:
If you need a backgroundColor to persist through out the highlight animation, don't use the backgroundColor property of UIView instead you can try (probably with-in tableview:cellForRowAtIndexPath:):
A CALayer with a background color:
UIColor *bgColor = [UIColor greenColor];
CALayer* layer = [CALayer layer];
layer.frame = viewThatRequiresBGColor.bounds;
layer.backgroundColor = bgColor.CGColor;
[cell.viewThatRequiresBGColor.layer addSublayer:layer];
or a CAGradientLayer:
UIColor *startColor = [UIColor redColor];
UIColor *endColor = [UIColor purpleColor];
CAGradientLayer* gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = viewThatRequiresBGColor.bounds;
gradientLayer.colors = #[(id)startColor.CGColor, (id)endColor.CGColor];
gradientLayer.locations = #[[NSNumber numberWithFloat:0],[NSNumber numberWithFloat:1]];
[cell.viewThatRequiresBGColor.layer addSublayer:gradientLayer];
I've also used a CALayer.border technique to provide a custom UITableView seperator:
// We have to use the borderColor/Width as opposed to just setting the
// backgroundColor else the view becomes transparent and disappears during
// the cell's selected/highlighted animation
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];
When you start dragging a UITableViewCell, it calls setBackgroundColor: on its subviews with a 0-alpha color. I worked around this by subclassing UIView and overriding setBackgroundColor: to ignore requests with 0-alpha colors. It feels hacky, but it's cleaner than any of the other solutions I've come across.
#implementation NonDisappearingView
-(void)setBackgroundColor:(UIColor *)backgroundColor {
CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
if (alpha != 0) {
[super setBackgroundColor:backgroundColor];
}
}
#end
Then, I add a NonDisappearingView to my cell and add other subviews to it:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
UIView *background = [cell viewWithTag:backgroundTag];
if (background == nil) {
background = [[NonDisappearingView alloc] initWithFrame:backgroundFrame];
background.tag = backgroundTag;
background.backgroundColor = backgroundColor;
[cell addSubview:background];
}
// add other views as subviews of background
...
}
return cell;
}
Alternatively, you could make cell.contentView an instance of NonDisappearingView.
My solution is saving the backgroundColor and restoring it after the super call.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
UIColor *bgColor = self.textLabel.backgroundColor;
[super setSelected:selected animated:animated];
self.textLabel.backgroundColor = bgColor;
}
You also need to do the same thing with -setHighlighted:animated:.
Found a pretty elegant solution instead of messing with the tableView methods. You can create a subclass of UIView that ignores setting its background color to clear color. Code:
class NeverClearView: UIView {
override var backgroundColor: UIColor? {
didSet {
if UIColor.clearColor().isEqual(backgroundColor) {
backgroundColor = oldValue
}
}
}
}
Obj-C version would be similar, the main thing here is the idea
I created a UITableViewCell category/extension that allows you to turn on and off this transparency "feature".
You can find KeepBackgroundCell on GitHub
Install it via CocoaPods by adding the following line to your Podfile:
pod 'KeepBackgroundCell'
Usage:
Swift
let cell = <Initialize Cell>
cell.keepSubviewBackground = true // Turn transparency "feature" off
cell.keepSubviewBackground = false // Leave transparency "feature" on
Objective-C
UITableViewCell* cell = <Initialize Cell>
cell.keepSubviewBackground = YES; // Turn transparency "feature" off
cell.keepSubviewBackground = NO; // Leave transparency "feature" on
Having read through all the existing answers, came up with an elegant solution using Swift by only subclassing UITableViewCell.
extension UIView {
func iterateSubViews(block: ((view: UIView) -> Void)) {
for subview in self.subviews {
block(view: subview)
subview.iterateSubViews(block)
}
}
}
class CustomTableViewCell: UITableViewCell {
var keepSubViewsBackgroundColorOnSelection = false
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
// MARK: Overrides
override func setSelected(selected: Bool, animated: Bool) {
if self.keepSubViewsBackgroundColorOnSelection {
var bgColors = [UIView: UIColor]()
self.contentView.iterateSubViews() { (view) in
guard let bgColor = view.backgroundColor else {
return
}
bgColors[view] = bgColor
}
super.setSelected(selected, animated: animated)
for (view, backgroundColor) in bgColors {
view.backgroundColor = backgroundColor
}
} else {
super.setSelected(selected, animated: animated)
}
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
if self.keepSubViewsBackgroundColorOnSelection {
var bgColors = [UIView: UIColor]()
self.contentView.iterateSubViews() { (view) in
guard let bgColor = view.backgroundColor else {
return
}
bgColors[view] = bgColor
}
super.setHighlighted(highlighted, animated: animated)
for (view, backgroundColor) in bgColors {
view.backgroundColor = backgroundColor
}
} else {
super.setHighlighted(highlighted, animated: animated)
}
}
}
All we need is to override the setSelected method and change the selectedBackgroundView for the tableViewCell in the custom tableViewCell class.
We need to add the backgroundview for the tableViewCell in cellForRowAtIndexPath method.
lCell.selectedBackgroundView = [[UIView alloc] init];
Next I have overridden the setSelected method as mentioned below.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
UIImageView *lBalloonView = [self viewWithTag:102];
[lBalloonView setBackgroundColor:[[UIColor hs_globalTint] colorWithAlphaComponent:0.2]];
UITextView *lMessageTextView = [self viewWithTag:103];
lMessageTextView.backgroundColor = [UIColor clearColor];
UILabel *lTimeLabel = [self viewWithTag:104];
lTimeLabel.backgroundColor = [UIColor clearColor];
}
Also one of the most important point to be noted is to change the tableViewCell selection style. It should not be UITableViewCellSelectionStyleNone.
lTableViewCell.selectionStyle = UITableViewCellSelectionStyleGray;

UIScrollView setZoomScale not working?

I am struggeling with my UIScrollview to get it to zoom-in the underlying UIImageView. In my view controller I set
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return myImageView;
}
In the viewDidLoad method I try to set the zoomScale to 2 as follows (note the UIImageView and Image is set in Interface Builder):
- (void)viewDidLoad {
[super viewDidLoad];
myScrollView.contentSize = CGSizeMake(myImageView.frame.size.width, myImageView.frame.size.height);
myScrollView.contentOffset = CGPointMake(941.0, 990.0);
myScrollView.minimumZoomScale = 0.1;
myScrollView.maximumZoomScale = 10.0;
myScrollView.zoomScale = 0.7;
myScrollView.clipsToBounds = YES;
myScrollView.delegate = self;
NSLog(#"zoomScale: %.1f, minZoolScale: %.3f", myScrollView.zoomScale, myScrollView.minimumZoomScale);
}
I tried a few variations of this, but the NSLog always shows a zoomScale of 1.0.
Any ideas where I screw this one up?
I finally got this to work. what caused the problem was the delegate call being at the end. I now moved it up and .... here we go.
New code looks like this:
- (void)viewDidLoad {
[super viewDidLoad];
myScrollView.delegate = self;
myScrollView.contentSize = CGSizeMake(myImageView.frame.size.width, myImageView.frame.size.height);
myScrollView.contentOffset = CGPointMake(941.0, 990.0);
myScrollView.minimumZoomScale = 0.1;
myScrollView.maximumZoomScale = 10.0;
myScrollView.zoomScale = 0.7;
myScrollView.clipsToBounds = YES;
}
Here is another example I made. This one is using an image that is included in the resource folder. Compared to the one you have this one adds the UIImageView to the view as a subview and then changes the zoom to the whole view.
-(void)viewDidLoad{
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:#"random.jpg"];
imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
[(UIScrollView *) self.view setContentSize:[image size]];
[(UIScrollView *) self.view setMaximumZoomScale:2.0];
[(UIScrollView *) self.view setMinimumZoomScale:0.5];
}
I know this is quite late as answers go, but the problem is that your code calls zoomScale before it sets the delegate. You are right the other things in there don't require the delegate, but zoomScale does because it has to be able to call back when the zoom is complete. At least that's how I think it works.
My code must be completely crazy because the scale that I use is completely opposite to what tutorials and others are doing. For me, minScale = 1 which indicates that the image is fully zoomed out and fits the UIImageView that contains it.
Here's my code:
[self.imageView setImage:image];
// Makes the content size the same size as the imageView size.
// Since the image size and the scroll view size should be the same, the scroll view shouldn't scroll, only bounce.
self.scrollView.contentSize = self.imageView.frame.size;
// despite what tutorials say, the scale actually goes from one (image sized to fit screen) to max (image at actual resolution)
CGRect scrollViewFrame = self.scrollView.frame;
CGFloat minScale = 1;
// max is calculated by finding the max ratio factor of the image size to the scroll view size (which will change based on the device)
CGFloat scaleWidth = image.size.width / scrollViewFrame.size.width;
CGFloat scaleHeight = image.size.height / scrollViewFrame.size.height;
self.scrollView.maximumZoomScale = MAX(scaleWidth, scaleHeight);
self.scrollView.minimumZoomScale = minScale;
// ensure we are zoomed out fully
self.scrollView.zoomScale = minScale;
This works as I expect. When I load the image into the UIImageView, it is fully zoomed out. I can then zoom in and then I can pan the image.