UIButton isn't responding to my touches on collectionView cells? - ios

I'm creating collectionView and inside that in every cell I'm creating few buttons horizontally but those buttons aren't responding to my target selector.
Here is my code.
ImplementationView.h
-(IBAction)tagClicked:(UIButton*)sender;
In ImplementationView.m
-(void)configureScrapCell:(UICollectionViewCell*) cell forScrapDict:(ScrapDictionary *)dict forIndexPath:(NSIndexPath*){
UIView *tagView = (UIView*)[cell viewWithTag:17];
UIView *layerTagView = (UIView*)[cell viewWithTag:18];
CGFloat x = 0.0;
if (layerTagView) {
[layerTagView removeFromSuperview];
}
layerTagView = [[UIView alloc] init];
layerTagView.tag = 18;
[tagView addSubview:layerTagView];
if ([dict.SDtags count]>0) {
int tagIndex = 1;
for (NSString *tag in dict.SDtags) {
CGSize width = [tag sizeWithFont:[UIFont systemFontOfSize:16]];
UIButton *scrapTag = [[UIButton alloc]initWithFrame:CGRectMake(x, 0,100, 30)];
[scrapTag setBackgroundColor:[UIColor greenColor]];
[scrapTag.titleLabel setFont:[UIFont systemFontOfSize:14]];
// [scrapTag setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
if (brightness > 150) {
[scrapTag setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}else {
[scrapTag setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
[scrapTag setTitle:[NSString stringWithFormat:#" #%#",tag] forState:UIControlStateNormal];
// [scrapTag sizeToFit];
[scrapTag setUserInteractionEnabled:YES];
tagIndex++;
NSString *tagString = #"";
tagString = [tagString stringByAppendingString:tag];
if ([tagString length]>32 || tagIndex>4) {
break;
}
[scrapTag addTarget:self action:#selector(tagClicked:) forControlEvents:UIControlEventTouchUpInside];
[layerTagView addSubview:scrapTag];
NSLog(#"%f",scrapTag.frame.size.width);
// scrapTag.frame = CGRectMake(x, scrapTag.frame.origin.y, tagView.frame.size.width, 30);
x += scrapTag.frame.size.width +2;
}
}
[tagView setBackgroundColor:[UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:0.5]];
[layerTagView setBackgroundColor:[UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:0.5]];
Now in different class where I'm defining the action of these button Clicked. ImplementationView class is acting as delegate for NewClass.
NewClass.h
#import ImplementationView.h
#interface NewClass : ImplementationView
NewClass.m
-(IBAction)tagClicked:(UIButton *)sender {
[[[UIAlertView alloc]initWithTitle:#"LOL" message:[NSString stringWithFormat:#"%#",sender.titleLabel.text] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil]show ];
NSLog(#"testing tag clicked");
}
Let me know if you need any other help to make question clear. Any help will be really appreciated. Thanks in advance.

Your buttons are not on the layerTagView bounds.
You need to set layerTagView frame/size. In your code the size of layerTagView is (0,0).
For check my suggestions you can set masksToBounds to YES or change the background color for layerTagView to blue or any other color.
tagView.layer.masksToBounds = YES;
layerTagView.layer.masksToBounds = YES;

Related

getting element from array one by one and createbutton

I have a UItextFeild as search bar on clicking a tableview with suggestion open.now i want to click on that row and make a button with its label in below view as described in image .how can i acheive this
I want it one by one means when i click on row it create a button on view and UITableView hide then again i start searching and on again clicking on some other row make a button with different value of X.
_selectednames = [NSMutableArray arrayWithCapacity:self.sortedArray.count];
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// MGContactItemsModel *model = _arrayForContacts[indexPath.row];
self.searchText.text = [NSString stringWithFormat:#"%#",[_sortedArray objectAtIndex:indexPath.row]];
self.tableView.hidden = YES;
[_selectednames addObject:_searchText.text];
for (int i; i < _selectednames.count ; i++) {
[self makeLabelsAndButtons:i];
}
now in my makeLabelsAndButtons funtion i done something like this
CGFloat xOffset = 10.0f;
int buttonCount = 0;
CGRect buttonFrame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
NSString *nameString = [self.selectednames objectAtIndex:indexPath];
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
//_button.frame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
for(int i=buttonCount; i >0;i++) {
xOffset = xOffset+10;
buttonFrame.origin.x += buttonFrame.size.width+xOffset;
}
_button.frame = buttonFrame;
buttonCount++;
_button.tag = indexPath;
//button.center = CGPointMake(xOffset, 10.0f);
//[button setBackgroundImage:[UIImage imageNamed:picString] forState: UIControlStateNormal];
[_button setTitle:self.selectednames[indexPath] forState:UIControlStateNormal];
_button.backgroundColor = [UIColor lightGrayColor];
_button.titleLabel.font = [UIFont fontWithName:#"Arial" size:8.0f];
_button.layer.cornerRadius = 10.0f;
_button.layer.masksToBounds = YES;
[self.buttonView addSubview:_button];
NSLog(#"name: %#", nameString);
also on clicking button it will removed.any help would be thankful.
It works for me.Please try it.
y=20;
x=20;
for (int i=0; i<[arrAssignUsers count]; i++) {
CGRect screenRect=[[UIScreen mainScreen]bounds];
CGFloat screenWidth=screenRect.size.width;
[arrBtnStatus addObject:[NSNumber numberWithBool:NO]];
NSString *strNames=[arrAssignUsers objectAtIndex:i];
stringsize=[strNames sizeWithAttributes:
#{NSFontAttributeName: [UIFont systemFontOfSize:20.0f]}];
btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
CGFloat m=x+stringsize.width+10;
CGFloat n=screenWidth-20;
if (m<=n) {
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width +10;
}
else
{
y=y+stringsize.height+10;
x=20;
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width+10;
}
[btn setTitle:self.arrAssignUsers[i] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.tag=i;
[btn addTarget:self
action:#selector(notifyButtonPressedInEditTask:) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor=WHITE_COLOR;
btn.layer.cornerRadius=10;
[btn.layer setMasksToBounds:YES];
btn.layer.borderWidth=2.0f;
btn.layer.borderColor=[UIColor orangeColor].CGColor;
[self checkNotifybtnStatus:btn];
[cell addSubview:btn];
}
}
It may helps to you.Thank you
You can use UICollectionView to create buttons. All you need to do is
1. Create custom cell with button as you want
2. When you tap on table view cell, add item to array and reload UICollectionView
3. Show buttons and it will automatically add scrollview for you.
When you tap on UICollectionView cell, remove object from array and reload UICollectionView again.
This will more easy as compared to adding buttons and setting frames.
And design UICollectionView cell in such way that it will same length as your text, use NSLayoutConstraints for it. It will work fast and smooth.
Code will be minimum and reusable.
Try out this working code...
Take UIScrollView in your Xib for buttons
//Adding menu buttons
btnArray = #[#"SYMPTOMATIC", #"SOCIAL", #"VOCATIONAL", #"PERSONAL"];
[self addButtonsInScrollMenu:btnArray];
/**
* Add Menu Buttons in Menu Scroll View
*
* #param buttonArray Array containing all menu button title
*/
#pragma mark - Add Menu Buttons in Menu Scroll View
-(void) addButtonsInScrollMenu:(NSArray *)buttonArray
{
CGFloat buttonHeight = self.menuScrollView.frame.size.height;
CGFloat cWidth = 0.0f;
for (int i = 0 ; i<buttonArray.count; i++)
{
NSString *tagTitle = [buttonArray objectAtIndex:i];
CGFloat buttonWidth = [self widthForMenuTitle:tagTitle buttonEdgeInsets:kDefaultEdgeInsets];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(cWidth, 0.0f, buttonWidth, buttonHeight);
[button setTitle:tagTitle forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:#"Roboto-Regular" size:12.0f];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.menuScrollView addSubview:button];
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, button.frame.size.height - kButtonBorderHeight, button.frame.size.width, kButtonBorderHeight)];
bottomView.backgroundColor = [UIColor darkTextColor];
bottomView.tag = 1001;
[button addSubview:bottomView];
if (i == 0)
{
button.selected = YES;
[bottomView setHidden:NO];
}
else
{
[bottomView setHidden:YES];
}
cWidth += buttonWidth;
}
NSLog(#"scroll menu width->%f",cWidth);
self.menuScrollView.contentSize = CGSizeMake(cWidth, self.menuScrollView.frame.size.height);
}

how to make UIView work as an scrollview

I need some serious help on this problem of mine where I need to work a UIView as an ScrollView. Below uploaded picture will clear all the doubts.
I have taken four buttons along with a UIView below them along with 4 container views which I have placed one above the other so as to work along with the four buttons.. What I want now is to work UIView as an ScrollView. Whenever I click any button, the View moves forward as well as the it changes the container view. And respective container view shows whenever I click a button.
Hi better you can use UIScrollView instead of UIView like:
//Declare it
NSMutableArray * buttonArray
int selectedIndex;
-(void)setUpSegmentBar {
NSArray * namesOfMenus =#[#"Button1",#"Button2",#"Button3",#"Button4",#"Button5"];
// Scrollview added on storyBoard
myScrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 2, self.view.frame.size.width, 40)];
CGFloat scrollWidth = 0.f;
buttonArray=[[NSMutableArray alloc]init];
for ( int j=0; j<namesOfMenus.count; j++)
{
NSString * name =[namesOfMenus objectAtIndex:j];
CGSize size = [name sizeWithAttributes:
#{NSFontAttributeName: [UIFont fontWithName:font_bold size:font_size_button]}];
CGSize textSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
CGFloat strikeWidth;
if (iPAD) {
strikeWidth = self.view.frame.size.width/5.5;
}else{
strikeWidth = textSize.width;
}
CGRect frame = CGRectMake(scrollWidth, 0,strikeWidth+20, 40);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTag:j];
button.frame = frame;
[button setBackgroundColor:[UIColor whiteColor]];
button.titleLabel.textColor=[UIColor whiteColor];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.layer.borderColor=[UIColor whiteColor].CGColor;
button.titleLabel.textAlignment=NSTextAlignmentCenter;
[button addTarget:self action:#selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:name forState:UIControlStateNormal];
// ScrollWidth As per Button Width
scrollWidth= scrollWidth+strikeWidth+20;
// to Check Which Button Is Selected.
if (j==selectedIndex) {
// If Selected Do UI Changes
button.backgroundColor=segment_selected_Color ;
[button setTitleColor:segment_disselected_Color forState:UIControlStateNormal];
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
[button addShaddow];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}else {
// Other Buttons
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
button.backgroundColor=segment_disselected_Color;
[button setTitleColor:segment_selected_Color forState:UIControlStateNormal];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else{
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}
// Add Buttons in Array
[buttonArray addObject:button];
// Add button on Scroll View
[myScrollView addSubview:button];
}
myScrollView.contentSize = CGSizeMake(scrollWidth, 30.f);
myScrollView.pagingEnabled = NO;
myScrollView.backgroundColor=[UIColor whiteColor];
[myScrollView setShowsHorizontalScrollIndicator:NO];
[myScrollView setShowsVerticalScrollIndicator:NO];
return myScrollView;
}
And For Handeling button action.
-(void)buttonEvent:(UIButton*)sender
{
NSInteger index= sender.tag;
selectedIndex= (int) index;
for(int i=0;i<buttonArray.count;i++)
{
UIButton * button =(UIButton*)[buttonArray objectAtIndex:i];
if (i==selectedIndex) {
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
button.backgroundColor=segment_selected_Color ;
[button setTitleColor:segment_disselected_Color forState:UIControlStateNormal];
[button addShaddow];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}else {
button.backgroundColor=segment_disselected_Color;
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
[button setTitleColor:segment_selected_Color forState:UIControlStateNormal];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else{
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}
}
CGRect frame1 = myScrollView.frame;
UIButton * bt=(UIButton*)[buttonArray objectAtIndex:index];
frame1 =bt.frame ;
// By using it button will scroll and show properly
[myScrollView scrollRectToVisible:frame1 animated:YES];
[self setupTableAfterClick];
}

How to change title color of a set of UIButtons created programmatically?

In my app I have created a few buttons programmatically using a for loop as shown below.It is for a HORIZONTAL TAB MENU
In the action,I have to highlight the selected button(and greyout the remaining button titles).How to do this?
It should look almost like the image below.
When a button is clicked,the clicked button title color should be
white and all other buttons should have a grey color.I know I can
access sender.titlecolor in the button action.But What about the other
buttons?
-(void)createButtons
{
float buttonMinX=10;
float buttonMinY=0;
scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _tabViewBackground.frame.size.width, _tabViewBackground.frame.size.height)];
ButtonIndex=0;
scrollView.showsHorizontalScrollIndicator = NO;
[_tabViewBackground addSubview:scrollView];
for (int i=0; i<_tabItemsListArray.count; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tintColor=[UIColor whiteColor];
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 1;
button.tag=i;
[button addTarget:self action:#selector(action:) forControlEvents:UIControlEventTouchUpInside];
UIFont *font1 = [UIFont fontWithName:#"HelveticaNeue-Thin" size:20.0f];
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setAlignment:NSTextAlignmentCenter];
NSDictionary *dict1 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleNone),
NSFontAttributeName:font1,
NSParagraphStyleAttributeName:style};
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:[_tabItemsListArray objectAtIndex:i] attributes:dict1]];
[button setAttributedTitle:attString forState:UIControlStateNormal];
buttonWidth= [self getWidthOfRect:button.titleLabel];
button.frame = CGRectMake(buttonMinX,buttonMinY,buttonWidth,_tabViewBackground.frame.size.height);
buttonMinX+=buttonWidth+05;
sublayer = [[UIView alloc]init];
sublayer.backgroundColor = [UIColor greenColor];
sublayer.tag=kButtonSelectrorTag+i;
sublayer.frame = CGRectMake(button.frame.origin.x,button.frame.size.height-2, button.frame.size.width,2);
[scrollView addSubview:sublayer];
sublayer.hidden=YES;
if (ButtonIndex==i)
{
sublayer.hidden=NO;
}
button.backgroundColor=[UIColor clearColor];
[scrollView addSubview:button];
}
scrollView.backgroundColor = [UIColor blueColor];
scrollView.contentSize = CGSizeMake(buttonMinX+10,_tabViewBackground.frame.size.height);
}
-(CGFloat)getWidthOfRect:(UILabel*)titleLabel
{
CGFloat widthIs =[titleLabel.text boundingRectWithSize:titleLabel.frame.size options:NSStringDrawingUsesDeviceMetrics attributes:#{ NSFontAttributeName:titleLabel.font }context:nil].size.width;
widthIs = ceilf(widthIs);
// NSLog(#"the width of yourLabel is %f", widthIs);
return widthIs+30;
}
- (void)action:(UIButton*)sender
{
for (int i=0; i<_tabItemsListArray.count; i++)
{
UIView *tabSelector = (UIView *)[self.view viewWithTag:kButtonSelectrorTag+i];
[tabSelector setHidden:YES];
}
UIView *tabSelector = (UIView *)[self.view viewWithTag:kButtonSelectrorTag+sender.tag];
[tabSelector setHidden:NO];
}
I have a button selector below every button.I should show one buttonSelector at a time.It is working great using the code in the action:
I've notice that you are using setAttributedTitle:forState:. You can set attributes for title in the same way but for UIControlStateSelected also.
Then, if you set button.selected = YES; attributes from UIControlStateSelected will apply.
If you set button.selected = NO; attributes from UIControlStateNormal will apply.
EDIT:
You can create your buttons like this:
NSInteger numberOfButtons = 10;
NSMutableArray *menuButtonsMutableArray = [[NSMutableArray alloc] initWithCapacity:numberOfButtons];
for (int i = 0; i < numberOfButtons; i++) {
UIButton *button = [UIButton new];
//layout your button somehow
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(menuButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
[menuButtonsMutableArray addObject:button];
}
self.menuButtonsArray = [menuButtonsMutableArray copy];
Then in action method:
- (void)menuButtonDidTap:(UIButton *)sender {
for (UIButton *button in self.menuButtonsArray) {
button.selected = (button == sender);
}
}
#IBOutlet var AllButtons: [UIButton]!
for button in AllButtons {
if button.backgroundColor == UIColor.red {
button.backgroundColor = compare.backgroundColor
}
}
Drag and drop all your buttons in AllButtons, then use for loop to access all the buttons and do whatever you like to do.
This is a simple example, hope it helps.

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;

How to get index of uiimage subview of uiscrollview

I need to detect selected image of uiimage which is placed inside scrollview.
My code is here:
int newscrollviewY = 40;
for(int i = 0; i<1; i++)
{
scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(5, newscrollviewY, 310, 100)];
scrollView.showsVerticalScrollIndicator = YES;
scrollView.scrollEnabled = YES;
scrollView.userInteractionEnabled = YES;
scrollView.backgroundColor = [UIColor clearColor];
scrollView.delegate=self;
int imgx = 1;
for(int img=0; img<[images count]; img++)
{
UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(imgx,0,100,100)];
imageView1.backgroundColor = [UIColor whiteColor];
imageView1.image = [images objectAtIndex:img];
imageView1.contentMode = UIViewContentModeScaleAspectFit;
[imageView1 setNeedsDisplay];
[imageView1 setUserInteractionEnabled:YES];
[imageView1 setMultipleTouchEnabled:YES];
[scrollView addSubview:imageView1];
imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
imageButton.frame = CGRectMake(imgx,0,100,100);
[imageButton addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
imageButton.tag = img;
[scrollView addSubview:imageButton];
imgx = imgx + 103;
}
Please help to detect selected image using imageButton or something else.
Replace your selector with buttonClicked:
be Sure that you are adding ":" after selector method. follow or replace the code below:
[imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
then Add the selector definantion in .m file
- (void) buttonClicked: (id) sender
{
// here you can get the tag of button.
NSInteger tag = ((UIButton *)sender).tag;
// do your implementation after this
}
Hope this will solve your issue. Enjoy Coding..!!
They way you have set it up the tag of the 'button' is already the number of the image in your array of images. So all you need to do is get the tag from the 'button'.
Make sure the button clicked function retrieves the tag from the sender(id) that you receive.
For example a bit like this:
- (IBAction)buttonClicked:(id)sender {
UIButton *button = (UIButton *)sender;
UIImage selectedImages = [images objectForKey: [button tag]];
}
As par you question if you are using UIImageview you have to use UITapGestureRecognizer that same like Button. you just need to add UITapGestureRecognizer like:-
for(int img=0; img<[images count]; img++)
{
UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(imgx,0,100,100)];
imageView1.backgroundColor = [UIColor whiteColor];
UITapGestureRecognizer *frameTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(frameTapGesture:)];
frameTapGesture.numberOfTapsRequired=1;
imageView1.image = [images objectAtIndex:img];
imageView1.contentMode = UIViewContentModeScaleAspectFit;
[imageView1 setNeedsDisplay];
[imageView1 setUserInteractionEnabled:YES];
[imageView1 setMultipleTouchEnabled:YES];
imageView1.tag=img;
[_imgView addGestureRecognizer:frameTapGesture];
[scrollView addSubview:imageView1];
}.
- (void)frameTapGesture:(UITapGestureRecognizer*)sender
{
UIView *view = sender.view; //cast pointer to the derived class if needed
NSLog(#"%d", view.tag);
}
Reduce your code There are No need to add Button with same Frame of ImageView For getting Click Event or you can also set Image of UIButton for you want to like use UIBUtton then remove UIImageview Code else you simply use UITapGestureRecognizer with getting click event using - (void)frameTapGesture:(UITapGestureRecognizer*)sender
Please try this code
for(int img=0; img<[images count]; img++)
{
imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
[imageButton setImage:[UIImage imageNamed:[images objectAtIndex:i]] forState:UIControlStateNormal];
imageButton.frame = CGRectMake(imgx,0,100,100);
[imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
imageButton.tag = img;
[scrollView addSubview:imageButton];
imgx = imgx + 103;
}
- (void) buttonClicked: (id) sender
{
UIButton *button = (UIButton *)sender;
UIImage selectedImage = button.currentImage;
}
set button target
[button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
// get Button Action
-(void) buttonAction:(UIButton *)sender
{
NSLog(#"%dl",sender.tag);
// do your implementation after this
}

Resources