Why is my TableView cell larger (higher) than its contents? (using autolayout) - ios

This is driving me crazy. I have a tableview with, in each cell, a simple UILabel at the top and a line of images underneath. Like this:
Here's some of the code I have for the TableView controller:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
// This project has only one cell identifier, but if you are have more than one, this is the time
NSString *reuseIdentifier = cellIdentifier;
MyCell *cell = [self.offscreenCells objectForKey:reuseIdentifier];
if (!cell) {
cell = [[MyCell alloc] init];
[cell setDelegate:self];
[self.offscreenCells setObject:cell forKey:reuseIdentifier];
}
[cell.titleLabel setText:#"UILabel - I want it smaller (wrapped)"];
NSString *url = #"http://assets.bizjournals.com/seattle/news/soccer%20ball%20square*304.jpg?v=1";
[self.imageView1 loadImageForURLString:url];
[self.imageView2 loadImageForURLString:url];
[self.imageView3 loadImageForURLString:url];
[self.imageView4 loadImageForURLString:url];
// Make sure the constraints have been added to this cell, since it may have just been created from scratch
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
// Do the layout pass on the cell, which will calculate the frames for all the views based on the constraints
[cell setNeedsLayout];
[cell layoutIfNeeded];
// Get the actual height required for the cell
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
// Add an extra point to the height to account for the cell separator, which is added between the bottom
// of the cell's contentView and the bottom of the table view cell.
height += 1;
return height;
}
And here's some relevant code in my tableview cell:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self.titleLabel setLineBreakMode:NSLineBreakByTruncatingTail];
[self.titleLabel setNumberOfLines:1];
[self.titleLabel setTextAlignment:NSTextAlignmentCenter];
[self.titleLabel setTextColor:[UIColor blackColor]];
[self.imagesView addSubview:self.titleLabel];
[self.imagesView addSubview:self.imageView1];
[self.imagesView addSubview:self.imageView2];
[self.imagesView addSubview:self.imageView3];
[self.imagesView addSubview:self.imageView4];
[self.contentView addSubview:self.titleLabel];
[self.contentView addSubview:self.imagesView];
self.contentView.backgroundColor = [UIColor whiteColor];
[self.titleLabel setBackgroundColor:[UIColor greenColor]];
[self.imagesView setBackgroundColor:[UIColor blueColor]];
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
}
return self;
}
- (void)updateConstraints
{
[super updateConstraints];
if (self.didSetupConstraints) {
return;
}
[UIView autoSetPriority:UILayoutPriorityRequired forConstraints:^{
[self.titleLabel autoSetContentCompressionResistancePriorityForAxis:ALAxisVertical];
}];
[self.titleLabel autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:kLabelVerticalInsets relation:NSLayoutRelationEqual];
[self.titleLabel autoPinEdgeToSuperviewEdge:ALEdgeLeading withInset:kLabelHorizontalInsets];
[self.titleLabel autoPinEdgeToSuperviewEdge:ALEdgeTrailing withInset:kLabelHorizontalInsets];
[UIView autoSetPriority:UILayoutPriorityRequired forConstraints:^{
[self.imagesView autoSetContentCompressionResistancePriorityForAxis:ALAxisVertical];
}];
[self.imagesView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.titleLabel withOffset:kLabelVerticalInsets relation:NSLayoutRelationLessThanOrEqual];
[self.imagesView autoPinEdgeToSuperviewEdge:ALEdgeLeading withInset:0 relation:NSLayoutRelationEqual];
[self.imagesView autoPinEdgeToSuperviewEdge:ALEdgeTrailing withInset:0 relation:NSLayoutRelationEqual];
[self.imagesView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
NSArray *subviews = #[self.imageView1, self.imageView2, self.imageView3, self.imageView4, self.imageView5];
[self.imageView1 autoMatchDimension:ALDimensionHeight toDimension:ALDimensionWidth ofView:self.imageView1];
[subviews autoMatchViewsDimension:ALDimensionHeight];
[subviews autoDistributeViewsAlongAxis:ALAxisHorizontal withFixedSpacing:10.0f insetSpacing:NO alignment:NSLayoutFormatAlignAllCenterY];
[subviews autoMatchViewsDimension:ALDimensionHeight];
[self.imageView1 autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.titleLabel withOffset:kLabelVerticalInsets relation:NSLayoutRelationEqual];
[self.imageView2 autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.titleLabel withOffset:kLabelVerticalInsets relation:NSLayoutRelationEqual];
[self.imageView3 autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.titleLabel withOffset:kLabelVerticalInsets relation:NSLayoutRelationEqual];
[self.imageView4 autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.titleLabel withOffset:kLabelVerticalInsets relation:NSLayoutRelationEqual];
[self.imageView5 autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.titleLabel withOffset:kLabelVerticalInsets relation:NSLayoutRelationEqual];
// Pin the images in the container so they appear
[self.imageView1 autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
[self.imageView1 autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
self.didSetupConstraints = YES;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
// need to use to set the preferredMaxLayoutWidth below.
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
self.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.titleLabel.frame);
}
So my question is this: Why isn't the UILabel wrapping my text? Am I pinning the views the right way?

Related

Cannot select/edit text in UITextView within UIScrollView

I have setup my UIScrollView with subviews like so using Masonry:
- (void)setupViews {
self.view.backgroundColor = [UIColor Background];
self.scrollView = [UIScrollView new];
self.scrollView.alwaysBounceVertical = YES;
[self.view addSubview:self.scrollView];
[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
self.contentView = [UIView new];
[self.scrollView addSubview:self.contentView];
self.scrollView.backgroundColor = [UIColor clearColor];
[self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.scrollView);
make.left.and.right.equalTo(self.view);
}];
self.imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.imageButton sd_setImageWithURL:[NSURL URLWithString:self.card.cardImageURL] forState:UIControlStateNormal];
[self.imageButton.imageView setContentMode:UIViewContentModeScaleAspectFill];
[self.contentView addSubview:self.imageButton];
[self.imageButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.and.right.equalTo(self.contentView);
make.height.equalTo(self.imageButton.mas_width).multipliedBy(3/4.0);
}];
self.textField = [UITextField new];
self.textField.backgroundColor = [UIColor whiteColor];
self.textField.font = kFontRegular(14);
self.textField.text = self.card.cardTitle;
[self.contentView addSubview:self.textField];
[self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.contentView).with.offset(8);
make.top.equalTo(self.imageButton.mas_bottom).with.offset(8);
make.right.equalTo(self.contentView).with.offset(-8);
make.height.equalTo(#(45));
}];
}
but it will not let me interact with the UITextField. what element here is preventing user interaction?
Your contentView's height will be zero. So it will never get some touch events. You should not use this constraint:
make.edges.equalTo(self.scrollView);
It will not get a correct value. Try to set top and height constraints for your contentView.
make.top.equalTo(#0);
make.height.equalTo(#700);

Width of contentView in UITableViewCell is different for each cell

In an UITableViewController defined in a Storyboard with Auto Layout enabled, a UITableViewCell subclass is created programatically (no IB prototype cell) and sets constraints through updateConstraints using PureLayout.
For some reason, the table view has each contentView with a different width, instead of using the const width of UITableView.
Here's the init and updateConstraints method of UITableViewCell subclass -
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
_nameLabel = [GTPaddedLabel newAutoLayoutView];
_nameLabel.font = [BQFontUtil standardFontSize:StandardFontSize1a bold:YES italic:NO];
_nameLabel.textColor = [UIColor blackColor];
_drugType = [UILabel newAutoLayoutView];
_drugType.font = [BQFontUtil standardFontSize:StandardFontSize0 bold:NO italic:NO];
_drugType.textColor = [UIColor darkGrayColor];
_drugType.textAlignment = NSTextAlignmentRight;
_genericsLabel = [UILabel newAutoLayoutView];
_genericsLabel.font = [BQFontUtil standardFontSize:StandardFontSize0 bold:NO italic:NO];
_genericsLabel.textColor = [UIColor darkGrayColor];
_regimen = [UILabel newAutoLayoutView];
_regimen.font = [BQFontUtil standardFontSize:StandardFontSize0 bold:NO italic:NO];
_regimen.textColor = [UIColor darkGrayColor];
[self.contentView addSubview:_nameLabel];
[self.contentView addSubview:_drugType];
[self.contentView addSubview:_genericsLabel];
[self.contentView addSubview:_regimen];
self.contentView.backgroundColor = [UIColor redColor];
}
return self;
}
- (void)updateConstraints {
if (!constraintsCreated) {
// [self.contentView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[UIView autoSetPriority:UILayoutPriorityRequired forConstraints:^{
[_nameLabel autoSetContentCompressionResistancePriorityForAxis:ALAxisVertical];
}];
[_nameLabel autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(8, 8, 0, 8) excludingEdge:ALEdgeBottom];
[_genericsLabel autoPinEdgeToSuperviewEdge:ALEdgeLeading withInset:16];
[_genericsLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_nameLabel withOffset:4];
[_genericsLabel autoSetDimension:ALDimensionHeight toSize:21];
[_drugType autoPinEdgeToSuperviewEdge:ALEdgeTrailing withInset:16];
[_drugType autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_nameLabel withOffset:4];
[_drugType autoPinEdge:ALEdgeLeading toEdge:ALEdgeTrailing ofView:_genericsLabel withOffset:8];
[_drugType autoSetDimension:ALDimensionHeight toSize:21];
[_regimen autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_genericsLabel withOffset:2];
[_regimen autoSetDimension:ALDimensionHeight toSize:21];
[_regimen autoPinEdgeToSuperviewEdge:ALEdgeTrailing withInset:16];
[_regimen autoPinEdgeToSuperviewEdge:ALEdgeLeading withInset:16];
[_regimen autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:8];
constraintsCreated = YES;
}
[super updateConstraints];
}
Why does contentView (brown color) doesn't have the same width as the table view?
Maybe that's a workaround, it works well when I'm constraining contentView's width to cell's width -
- (void)updateConstraints {
if (!constraintsCreated) {
[self.contentView autoSetDimension:ALDimensionWidth toSize:self.frame.size.width];
...
}
}

UIScrollView paging disabled after rotation

Following is my code for App Tour using UIScrollView with paging enabled using AutoLayout (Masonry) It works fine in Portrait but when I rotate paging gets disabled so it doesn't work in Landscape. Then it doesn't work in Portrait mode either. Can someone help what's wrong here?
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor clearColor];
self.scrollView = [UIScrollView new];
self.scrollView.backgroundColor = [UIColor clearColor];
self.scrollView.scrollEnabled = YES;
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;
self.scrollView.showsHorizontalScrollIndicator = NO;
[self.view addSubview:self.scrollView];
[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
UIImageView *esImageview1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"CommonResources.bundle/page1"]];
esImageview1.contentMode = UIViewContentModeScaleAspectFit;
esImageview1.backgroundColor = [UIColor clearColor];
esImageview1.userInteractionEnabled = YES;
[self.scrollView addSubview:esImageview1];
[esImageview1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.bottom.equalTo(self.scrollView);
make.width.height.equalTo(self.view);
}];
UIImageView *esImageview2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"CommonResources.bundle/page2"]];
esImageview2.contentMode = UIViewContentModeScaleAspectFit;
esImageview2.backgroundColor = [UIColor clearColor];
esImageview2.userInteractionEnabled = YES;
[self.scrollView addSubview:esImageview2];
[esImageview2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(esImageview1.mas_right);
make.top.bottom.equalTo(self.scrollView);
make.width.height.equalTo(self.view);
}];
UIImageView *esImageview3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"CommonResources.bundle/page3"]];
esImageview3.contentMode = UIViewContentModeScaleAspectFit;
esImageview3.backgroundColor = [UIColor clearColor];
esImageview3.userInteractionEnabled = YES;
[self.scrollView addSubview:esImageview3];
[esImageview3 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(esImageview2.mas_right);
make.top.bottom.equalTo(self.scrollView);
make.width.height.equalTo(self.view);
}];
self.pageControl = [UIPageControl new];
self.pageControl.numberOfPages = 3;
self.pageControl.currentPage = 0;
self.pageControl.backgroundColor = [UIColor clearColor];
[self.view addSubview:self.pageControl];
[self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.view);
make.height.equalTo(#40);
make.top.equalTo(self.view).with.offset(40);
}];
UILabel *titleLabel = [UILabel new];
titleLabel.text = #"App Tour";
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.font = [UIFont fontWithName:#"Helvetica-Light" size:16];
titleLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:titleLabel];
[titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.view);
make.height.equalTo(#40);
make.top.equalTo(self.view).with.offset(20);
}];
UIButton *doneButton = [UIButton new];
[doneButton.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Light" size:16]];
[doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[doneButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
[doneButton setTitle:#"Done" forState:UIControlStateNormal];
[doneButton addTarget:self action:#selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
doneButton.backgroundColor = [UIColor clearColor];
[self.view addSubview:doneButton];
[doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.view);
make.height.equalTo(#40);
make.width.equalTo(#70);
make.top.equalTo(self.view).with.offset(20);
}];
}
- (void)doneButtonPressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width*self.pageControl.numberOfPages, self.view.frame.size.height);
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
I'm guessing its getting covered up by another view or something similar to that. Try subclassing the UIScrollView and implementing the following method to check if its responding to your touches at all.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"OMG TOUCHES WORK, NOW WHAT?");
}
You can easily check if it was getting covered up by forcing it to be in front. Call this line of code in the callback for rotation in the UIViewController containing the UIScrollView. It should fix the problem. You may have to subclass the UIView for the controller and put this method in the didLayoutSubviews method instead, not quite sure, depends on your implementation.
[self.view bringSubViewToFront:self.scrollView];
Also check the frame and bounds before and after rotation and see if anything is out of place looking
I just wanted to reset Scrollview's contentsize in didRotateFromInterfaceOrientation delegate. Not sure why though because when I rotate, videDidLayoutSubview already gets called where I am already reseting content size.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width*self.pageControl.numberOfPages, self.view.frame.size.height);
}

IOS UITableview Scroll is not smooth in IOS6

And I complete IOS app in IOS 7 and its works fine IOS 7 and then I start converting my app to IOS 6 I face lot of problems.After a huge struggle I rectify almost all the issuse other that Performance issue
I am using UITableview to display all the contents and when I test my app in Iphone 5c there is no problem in scrolling the table view. And the I test my app in ipod retina list is not scrolling smoothly. It is one of the huge problem for me and also Its killing my time
To illustrate my issue I have added my tableview cell code below. Please Suggest me some quick solution
UITableviewCell Code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell ==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier]autorelease];
}
[[cell.contentView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
cell.selectionStyle = UITableViewCellEditingStyleNone;
UIView * contentview = [[[UIView alloc]init]autorelease];
UIImageView * userimage = [[[UIImageView alloc]init]autorelease];
UIImageView * itemimageview = [[[UIImageView alloc]init]autorelease];
UIView * bottomview = [[[UIView alloc]init]autorelease];
UILabel * imagenameLable = [[[UILabel alloc]init]autorelease];
UILabel * usernameLable = [[[UILabel alloc]init]autorelease];
UILabel * itemcostLable = [[[UILabel alloc]init]autorelease];
UIButton*fancybtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton * addrditbtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton * commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UILabel * noofcommentsLable = [[[UILabel alloc]init]autorelease];
// [contentBgImageview setImage:[UIImage imageNamed:#"item_bg.png"]];
[itemimageview setAutoresizesSubviews:YES];
// [itemimageview setContentMode:UIViewContentModeScaleAspectFill];
[itemimageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"item_url_main_350"]]]];
[itemimageview setContentMode:UIViewContentModeScaleAspectFit];
[itemimageview setTag:indexPath.row];
[userimage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"user_url_main_70"]]]];
[bottomview setBackgroundColor:[UIColor colorWithRed:200/255 green:54/255 blue:54/255 alpha:0.4]];
[bottomview setBackgroundColor:[UIColor colorWithRed:255 green:255 blue:255 alpha:1]];
// [bottomview setAlpha:0.5];
[imagenameLable setText:[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"item_title"]];
[imagenameLable setTextColor:[UIColor blackColor]];
[imagenameLable setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
[imagenameLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:imagenameLable];
[usernameLable setText:[NSString stringWithFormat:#"#%#",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"sellername"]]];
[usernameLable setTextColor:[UIColor grayColor]];
[usernameLable setFont:[UIFont fontWithName:#"Helvetica" size:10]];
[usernameLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:usernameLable];
[itemcostLable setText:[NSString stringWithFormat:#"%# %#",delegate.currencyStr,[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"price"]]];
[itemcostLable setTextColor:[UIColor grayColor]];
[itemcostLable setFont:[UIFont fontWithName:#"Helvetica-Bold" size:16]];
[itemcostLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:itemcostLable];
// [addrditbtn setImage:[UIImage imageNamed:#"add.png"] forState:UIControlStateNormal];
if ([[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"liked"]isEqualToString:#"No"])
{
[fancybtn setImage:[UIImage imageNamed:#"fantacybtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
else
{
[fancybtn setImage:[UIImage imageNamed:#"fantacydbtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
NSString*itemid=[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"];
if ([delegate.fantacyitemsArray containsObject:itemid]) {
[fancybtn setImage:[UIImage imageNamed:#"fantacydbtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
if ([delegate.unfantacyitemsArray containsObject:itemid]) {
[fancybtn setImage:[UIImage imageNamed:#"fantacybtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
fancybtn.tag=[itemid intValue];
[fancybtn addTarget:self action:#selector(fancyBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
addrditbtn.tag=[itemid intValue];
[addrditbtn addTarget:self action:#selector(addtolistBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[commentBtn setImage:[UIImage imageNamed:#"commentnew.png"] forState:UIControlStateNormal];
[commentBtn setUserInteractionEnabled:YES];
commentBtn.tag=indexPath.row;
[commentBtn addTarget:self action:#selector(commentBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIButton * usernameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[usernameBtn setUserInteractionEnabled:YES];
usernameBtn.tag=indexPath.row;
[usernameBtn addTarget:self action:#selector(usernameBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[noofcommentsLable setTextColor:[UIColor grayColor]];
[noofcommentsLable setFont:[UIFont fontWithName:#"Helvetica" size:12]];
int commentcount = 0;
if([delegate.newaddedcommentDict objectForKey:[NSString stringWithFormat:#"%#Array",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"]]])
{
commentcount = [[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"commentcount"]intValue]+[[delegate.newaddedcommentDict objectForKey:[NSString stringWithFormat:#"%#Array",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"]]]count];
}
else
{
commentcount = [[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"commentcount"]intValue];
}
[noofcommentsLable setText:[NSString stringWithFormat:#"%d",commentcount]];
UIScrollView * scroll = [[[UIScrollView alloc]init]autorelease];
// [scroll setScrollEnabled:NO];
[scroll setUserInteractionEnabled:YES];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(gestureAction:)];
[recognizer setNumberOfTapsRequired:1];
scroll.userInteractionEnabled = YES;
[scroll addGestureRecognizer:recognizer];
[itemcostLable setTextAlignment:NSTextAlignmentRight];
[bottomview setFrame:CGRectMake(0,3,300,37)];
[itemimageview setFrame:CGRectMake(0,0,300,240)];
CGSize size;
if ([[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"width"]!=[NSNull null]||[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"height"]!=[NSNull null])
{
size= [self aspectScaledImageSizeForImageView:itemimageview width:[[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"width"]floatValue] height:[[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"height"]floatValue]];
}
else
{
size = CGSizeMake(100,100);
}
[itemimageview setFrame:CGRectMake((300-size.width)/2,0,size.width,size.height)];
[scroll setFrame:CGRectMake(0,43,300,size.height)];
//place holder image
UIImageView * placeholderimageview = [[[UIImageView alloc]init]autorelease];
[placeholderimageview setFrame:CGRectMake(130,0,40,size.height)];
[placeholderimageview setImage:[UIImage imageNamed:#"57.png"]];
[placeholderimageview setContentMode:UIViewContentModeScaleAspectFit];
// [itemimageview setBackgroundColor:[UIColor redColor]];
[imagenameLable setFrame:CGRectMake(40,5,160,15)];
[usernameLable setFrame:CGRectMake(40,20,160,15)];
[usernameBtn setFrame:CGRectMake(0,5,200,30)];
[itemcostLable setFrame:CGRectMake(220,0,70,40)];
[fancybtn setFrame:CGRectMake(5,size.height+48,78,25)];
[commentBtn setFrame:CGRectMake(221,size.height+48,40,25)];
[noofcommentsLable setFrame:CGRectMake(240,size.height+48,20,25)];
[addrditbtn setFrame:CGRectMake(265,size.height+48,27,25)];
// [commentBtn setFrame:CGRectMake(191,size.height+48,40,25)];
// [noofcommentsLable setFrame:CGRectMake(211,size.height+48,20,25)];
// [addrditbtn setFrame:CGRectMake(236,size.height+48,27,25)];
// [cartbtn setFrame:CGRectMake(268,size.height+48,27,25)];
[contentview setFrame:CGRectMake(10,5,300,size.height+78)];
[userimage setFrame:CGRectMake(5,5,30,30)];
[scroll setBackgroundColor:[UIColor colorWithRed:0.976 green:0.976 blue:0.976 alpha:1]];
[scroll setBackgroundColor:[UIColor clearColor]];
contentview.clipsToBounds = NO;
contentview.layer.masksToBounds = NO;
contentview.layer.shadowColor = [[UIColor grayColor] CGColor];
contentview.layer.shadowOffset = CGSizeMake(0,1);
contentview.layer.shadowOpacity = 0.2;
contentview.layer.shadowRadius = 0.6;
contentview.layer.cornerRadius = 6.0; // set as you want.
[bottomview setBackgroundColor:[UIColor clearColor]];
userimage.layer.cornerRadius = 15.0;
userimage.layer.masksToBounds = YES;
[itemimageview setUserInteractionEnabled:YES];
[scroll setBackgroundColor:[UIColor clearColor]];
[bottomview setBackgroundColor:[UIColor clearColor]];
[contentview setBackgroundColor:[UIColor whiteColor]];
//place holder image
[contentview addSubview:scroll];
[scroll addSubview:placeholderimageview];
[scroll addSubview:itemimageview];
[contentview addSubview:bottomview];
[contentview addSubview:fancybtn];
[contentview addSubview:addrditbtn];
[contentview addSubview:commentBtn];
[contentview addSubview:noofcommentsLable];
[contentview addSubview:userimage];
[contentview addSubview:usernameLable];
[contentview addSubview:usernameBtn];
[cell.contentView addSubview:contentview];
[cell setBackgroundColor:[UIColor clearColor]];
[cell.contentView setBackgroundColor:[UIColor clearColor]];
// Configure the cell...
return cell;
}
Its because in every time when cellForRowAtIndexPath: method called you recreating all subviews again.
You must do it only once.
Make a class that inherits from UITableViewCell.
//MyCell.h file
#interface MyCell : UITableViewCell
//here declare all views that you need, e.g.
#property (strong, nonatomic) UILabel *imagenameLable;
#property (strong, nonatomic) UILabel *usernameLable;
// and so on. But only those, that you mast set value (or read values) outside of this class.
// the other views declare in MyClass.m file, so they are for private use (eg. contentview,etc...)
#end
//MyCell.m file
#interface MyCell()
// here declare private properties
#property (strong, nonatomic) UIView* contentview;
// and so on...
#end
#implementation
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self setupUI];
}
return self;
}
- (void)setupUI
{
//and finally, in this method build your views, i.e. allocate your views, add subview of this cell, set frames, font to labels, text colors, etc...
//e.g.
self.contentview = [[[UIView alloc]init]autorelease];
self.contentview.clipsToBounds = NO;
self.contentview.layer.masksToBounds = NO;
self.contentview.layer.shadowColor = [[UIColor grayColor] CGColor];
self.contentview.layer.shadowOffset = CGSizeMake(0,1);
self.contentview.layer.shadowOpacity = 0.2;
self.contentview.layer.shadowRadius = 0.6;
self.contentview.layer.cornerRadius = 6.0; // set as you want.
// initialize other views
[self.contentview addSubview:self.scroll];
[self.scroll addSubview:self.placeholderimageview];
[self.scroll addSubview:self.itemimageview];
[self.contentview addSubview:self.bottomview];
[self.contentview addSubview:self.fancybtn];
[self.contentview addSubview:self.addrditbtn];
[self.contentview addSubview:self.commentBtn];
[self.contentview addSubview:self.noofcommentsLable];
[self.contentview addSubview:self.userimage];
[self.contentview addSubview:self.usernameLable];
[self.contentview addSubview:self.usernameBtn];
[self.contentView addSubview:self.contentview];
// something like this.
}
#end
And finally
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"cell";
MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell ==nil)
{
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier]autorelease];
}
// here set values to properties of your cell. EG set text, change color if needed, change frame if needed, etc... But not remove and add them again!
cell.usernameLable.text = [NSString stringWithFormat:#"#%#",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"sellername"]]];
//etc...
return cell;
}
I found the solution for my code
This is because of
contentview.layer.shadowOffset = CGSizeMake(0,1);
contentview.layer.shadowOpacity = 0.2;
contentview.layer.shadowRadius = 0.6;
contentview.layer.cornerRadius = 6.0; // set as
Once I remove this line from my code Its works fine
There is lot of optimalization issues in your code. You should use Instruments with Time Profiler template to detect bottlenecks.
BTW, When you draw shadow of CALayer you should set CALayer's shadowPath property for outline of the shadow. This will speed up drawing your shadow much. Please refer documentation for more details.
dialogContainer.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:dialogContainer.bounds cornerRadius:dialogContainer.layer.cornerRadius].CGPath;

getting adjustsFontSizeToFitWidth to work with constraints for snug content

This is a little view control I've written to test out the issue I'm having with constraints and adjustsFontSizeToFitWidth. Its a little thing that add's and remove's words from a label to see how various content sizes in label_title effect the layout. The desired layout is snug around the label_title (with the label_count taking up the rest of the room). Unfortunately its not quite snug yet.
Here are 3 view states I've screen captured to illustrate the lack of snugness on the blue title which I'm trying to fix.
Following that is the full source of a view controller that will run this view.
#import "MainViewController.h"
#interface MainViewController ()
// stuff to test our problem with
#property(nonatomic,strong) UIButton * addButton;
#property(nonatomic,strong) UIButton * removeButton;
// our problem
#property(nonatomic,strong) UIView * view_labels;
#property(nonatomic,strong) UILabel * label_title;
#property(nonatomic,strong) UILabel * label_count;
#end
#implementation MainViewController
// synthesize for the views constraint mapping
#synthesize label_title;
#synthesize label_count;
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor grayColor]];
self.addButton = [self buttonWithTitle:#"Add Word"
selector:#selector(addButtonPressed) color:[UIColor greenColor]];
self.removeButton = [self buttonWithTitle:#"Remove Word"
selector:#selector(removeButtonPressed) color:[UIColor redColor]];
// view containing our troublesome labels
self.view_labels = [[UIView alloc] init];
[self.view addSubview:self.view_labels];
//[self.view_labels setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view_labels setBackgroundColor:[UIColor lightGrayColor]];
// label row 1
self.label_title = [self labelWithText:#"word" defaultFontSize:30.0 bgcolor:[UIColor blueColor]];
[self.view_labels addSubview:self.label_title];
// label row 2
self.label_count = [self labelWithText:#"77" defaultFontSize:40.0 bgcolor:[UIColor purpleColor]];
[self.view_labels addSubview:self.label_count];
NSDictionary *views = NSDictionaryOfVariableBindings(label_title, label_count);
NSDictionary *metrics = #{#"pad":#2};
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:#"V:|-(==pad)-[label_title(<=44)]-(==pad)-[label_count]-(==pad)-|"
options:0
metrics:metrics
views:views]];
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:#"|-(==pad)-[label_title]-(==pad)-|"
options:0
metrics:metrics
views:views]];
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:#"|-(==pad)-[label_count]-(==pad)-|"
options:0
metrics:metrics
views:views]];
}
#pragma mark - boiler plate stuff
-(UILabel*) labelWithText:(NSString*) text defaultFontSize:(float) fontSize bgcolor:(UIColor*) color
{
UILabel * label = [[UILabel alloc] init];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
[label setTextAlignment:NSTextAlignmentCenter];
[label setTextColor:[UIColor whiteColor]];
[label setAdjustsFontSizeToFitWidth:YES];
[label setNumberOfLines:0];
[label setMinimumScaleFactor:0.6];
[label setFont:[UIFont boldSystemFontOfSize:fontSize]];
[label setBackgroundColor:color];
[label setText:text];
return label;
}
-(UIButton*) buttonWithTitle:(NSString*) title selector:(SEL) selector color:(UIColor*) color
{
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:button];
[button setTitle:title forState:UIControlStateNormal];
[button setBackgroundColor:color];
[button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
return button;
}
-(void) viewWillLayoutSubviews{
[super viewWillLayoutSubviews];
float SQUARE_SIZE = 100;
[self.addButton setFrame:CGRectMake(0, self.view.frame.size.height-44.0, self.view.frame.size.width, 44.0)];
[self.removeButton setFrame:CGRectMake(0, self.view.frame.size.height-(44.0*2), self.view.frame.size.width, 44.0)];
[self.view_labels setFrame:CGRectMake(SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)];
}
-(void) addButtonPressed
{
NSString * text = self.label_title.text;
if (text == nil){
text = #"";
}
text = [NSString stringWithFormat:#"%#%#",text,#" word"];
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[self.label_title setText:text];
}
-(void) removeButtonPressed
{
NSString * text = self.label_title.text;
if (text == nil || [text isEqualToString:#""]){
return;
}
NSArray * array = [text componentsSeparatedByString:#" "];
text = #"";
for (int i = 0; i < [array count]-1; i++){
NSString * token = [array objectAtIndex:i];
text = [NSString stringWithFormat:#"%# %#",text,token];
}
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[self.label_title setText:text];
}
#end
If you are trying to fit the text in UILabel replace the your method by the following.
-(UILabel*)labelWithText:(NSString*) text defaultFontSize:(float) fontSize bgcolor:(UIColor*) color
{
#autoreleasepool {
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50,100,100)];
[label setTextAlignment:NSTextAlignmentCenter];
[label setTextColor:[UIColor whiteColor]];
[label setAdjustsFontSizeToFitWidth:YES];
[label setFont:[UIFont boldSystemFontOfSize:fontSize]];
[label setBackgroundColor:color];
[label setText:text];
[label setNumberOfLines:0];
while (fontSize > 0.0)
{
CGSize size = [text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, label.frame.size.height) lineBreakMode:NSLineBreakByWordWrapping];
if (size.height <= label.frame.size.height)
break;
fontSize -= 1.0;
}
[label setFont:[UIFont boldSystemFontOfSize:fontSize]];
return label;
}
}

Resources