So I have class called CSImageViews (subclass of uiview), that is essentially a row of UIImageViews enclosed in a single subclassed UIView.
I've added a custom init method like so (node/yaml contains uiimage name data):
- (id)initWithFrame:(CGRect)frame withNode:(NSDictionary *)node
{
self = [super initWithFrame:frame];
if (self) {
_node = node;
_imageViewYAML = [node objectForKey:#"items"];
_imageViews = [self getImageViewsForItems:_imageViewYAML];
}
return self;
}
And my getImageViewsforItems is like so (adds them all to subview):
-(NSArray *)getImageViewsForItems:(NSArray *)items
{
NSMutableArray *ivs = [NSMutableArray arrayWithCapacity:[items count]];
for (int i = 0; i < [items count]; i++) {
NSDictionary *item = [items objectAtIndex:i];
NSString *type = [item objectForKey:#"type"];
NSString *name = [item objectForKey:#"name"];
UIImage *image = [UIImage imageNamed:name];
UIImageView *iv = [[UIImageView alloc] init];
iv.image = image;
iv.tag = i;
[ivs addObject:iv];
[self addSubview:iv];
}
return ivs;
}
Now when I add this custom view to my main view like this nothing happens:
CSImageViews *imageViews = [[CSImageViews alloc] initWithFrame:frame withNode:node];
[view addSubview:imageViews];
But if I add this 'csimageviews' container into a new uiview first it appears:
CSImageViews *imageViews = [[CSImageViews alloc] initWithFrame:frame withNode:node];
UIView *v = [[UIView alloc] initWithFrame:frame];
[v addSubview:imageViews];
[view addSubview:v];
thoughts?
Stupid error by me. In this particular subclassed UIView I have a method that was called every time its parent view controller was shown. This method actually removed all subviews from the view... so I wasn't able to see the uiimageviews when I rendered it in the initial view... doh.
Related
help please. I have this code that shows me images in scrollview.:
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *imgNames = [[NSArray alloc] initWithObjects:#"ip1.jpg", #"ip2.jpg", #"ip3.jpg", #"ip4.jpg", #"ip5.jpg", #"ip6.jpg", #"ip7.jpg", #"ip8.jpg", #"ip9.jpg", #"ip10.jpg",#"ip11.jpg",#"ip12.jpg",#"ip13.jpg",#"ip14.jpg",#"ip15.jpg",#"ip16.jpg",#"ip17.jpg",#"ip18.jpg",#"ip19.jpg",#"ip20.jpg",#"ip21.jpg", nil];
// Setup the array of UIImageViews
NSMutableArray *imgArray = [[NSMutableArray alloc] init];
UIImageView *tempImageView;
for(NSString *name in imgNames) {
tempImageView = [[UIImageView alloc] init];
tempImageView.contentMode = UIViewContentModeScaleAspectFill;
tempImageView.image = [UIImage imageNamed:name];
[imgArray addObject:tempImageView];
}
CGSize pageSize = scrollViewBack.frame.size; // scrollView is an IBOutlet for our UIScrollView
NSUInteger page = 0;
for(UIView *view in imgArray) {
[scrollViewBack addSubview:view];
// This is the important line
view.frame = CGRectMake(pageSize.width * page++ + 40, 0, pageSize.width - 80, pageSize.height);
}
scrollViewBack.contentSize = CGSizeMake(pageSize.width * [imgArray count], pageSize.height);
}
Now, I want a UILabel, that will show me, Image name, when I will scroll. Help me please, I can't implement that. Thanks a lot.
In your second for loop you can acces to the indexes of the objects of imgArray and imgNames, so try this:
int idx = [imgArray indexOfObject:view];
NSString *strName = [imgNames objectAtIndex:idx];
//create the label
label.text=strName;
//add the label in the scrollView
If you want to show the label just when the new image is showed, keep the two arrays as iVars and use UIPageControl to track in wich page of the scrollview you are. (Sample code).
In your loop you could do something like this. Read the apple docs. Search google for how to make a label. Its not hard to learn this stuff if you just try.
for(NSString *name in imgNames) {
// ....
UILabel *label = [[UILabel alloc] initWithFrame:WHEREYOUWANTIT];
[label setText:name];
}
I created simple UIScrollView that have images. Each time an image pressed i want to change that image, how can I do it?
I creating this UIScrollView and initializing it with NSMutableArray with images.
UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame: CGRectMake (0,100,200,30)];
NSMutableArray = *images = [NSMutableArray alloc] initWithObjects: img1,img2,img3,nil];
for (int i=0; i<3; i++)
{
UIImageView *imageV = [UIImageView alloc];
[imageV setImage:[images objectAtIndex:i]];
[myScroll addSubview:imageV];
[imageV release];
}
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:#selector (changeImg:)];
[myScroll addGestureRecognizer: singleTap];
and the toucing I'm cathing with the touched place on the scroll:
- (void) singleTapGestureCaptured:(UITapGesturerecongnizer *) gesture
{
CGPoint touch = [gesture locationInView:myScroll];
}
By X,Y of touched item i know what image was selected
Here I need to change for example the first image of myScroll...How can i do it?
Add UITapGestureRecognizer on UIImageView and set its userInractionEnabled: YES which is NO by default for UIImageView.
UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame: CGRectMake (0,100,200,30)];
NSMutableArray = *images = [NSMutableArray alloc] initWithObjects: img1,img2,img3,nil];
for (int i=0; i<3; i++)
{
//In your question you didn't set `imageView` frame so correct it
UIImageView *imageV = [[UIImageView alloc]initWithFrame:yourFrame];
[imageV setImage:[images objectAtIndex:i]];
[imageV setUserInteractionEnabled:YES];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:#selector (changeImg:)];
[imageV addGestureRecognizer: singleTap];
[myScroll addSubview:imageV];
[imageV release];
}
After adding all imageView successfully you get them click like this :-
-(void)changeImg:(id)sender
{
UIGestureRecognizer *recognizer = (UIGestureRecognizer*)sender;
UIImageView *imageView = (UIImageView *)recognizer.view;
[imageView setImage:[UIImage imageNamed:#"anyImage.png"]];
}
Your application will crash because you are accessing the index 3, but there is not any object at index 3.
UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame: CGRectMake (0,100,200,30)];
NSMutableArray = *images = [NSMutableArray alloc] initWithObjects: img1,img2,img3,nil];
[myScroll addSubview:[images objectAtIndex:0];
[myScroll addSubview:[images objectAtIndex:1];
[myScroll addSubview:[images objectAtIndex:2];
Now you can access the image view with tagValue
-(void)changeImg :(UIGestureRecognizer*)recog
{
UIScrollView *scroll = (UIScrollView*)recog.view;
CGPoint point = scroll.contentOffset;
int imagetag = (point.y/scroll.frame.size.height);
UIImageView *image=(UIImageView*)[[scroll subviews] objectAtIndex:imagetag];
NSLog(#"Image tag = %d",image.tag);
image.image=[UIImage imageNamed:#"Icon-72.png"];
}
A simple implementation will be, if you use a custom button and change its image on its IBAction.. Still you can addGesture to ur UIImageView too and on the
if(recognizer.state == UIGestureRecognizerStateBegan)
you can change the image on runtime.
I hope this helps. Cheers!!
i want to create an application in one row of tableView there will be 4 images of button which will be loaded from server in background because if i directly load them than the table view will hang some. for this i have used this code for creating button in cell and performing to download images in background.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *hlCellID = #"hlCellID";
UITableViewCell *hlcell = [tableView dequeueReusableCellWithIdentifier:hlCellID];
if(hlcell == nil) {
hlcell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:hlCellID] autorelease];
hlcell.accessoryType = UITableViewCellAccessoryNone;
hlcell.selectionStyle = UITableViewCellSelectionStyleNone;
}
int section = indexPath.section;
NSMutableArray *sectionItems = [sections objectAtIndex:section];
int n = [sectionItems count];
int i = 0, j = 0, tag = 1;
int x = 10;
int y = 30;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (i = 1; i<= n ; i++) //[arr count]
{
for(j=1; j<=4;j++)
{
if (i>=n) break;
Item *item = [sectionItems objectAtIndex:i];
CGRect rect = CGRectMake(x = x, y = y, 68, 65);
UIButton *button=[[UIButton alloc] initWithFrame:rect];
[button setFrame:rect];
UIImage *buttonImageNormal=[UIImage imageNamed:item.image];
[button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
[button setContentMode:UIViewContentModeCenter];
// set the image to be loaded (using the same one here but could/would be different)
NSURL *imgURL = [NSURL URLWithString:#"http://londonwebdev.com/wp-content/uploads/2010/07/featured_home.png"];
// Create an array with the URL and imageView tag to
// reference the correct imageView in background thread.
NSMutableArray *arr = [[NSArray alloc] initWithObjects:imgURL, [NSString stringWithFormat:#"%d", tag], nil ];
// Start a background thread by calling method to load the image
[self performSelectorInBackground:#selector(loadImageInBackground:) withObject:arr];
// button.tag = [tagValue intValue];
button.tag = tag;
//NSLog(#"....tag....%d", button.tag);
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[hlcell.contentView addSubview:button];
[button release];
tag++;
x = x + 77;
}
x = 10;
y = y + 74;
}
[pool release];
return hlcell;
}
the above code work perfectly but when i download the images and trying to assign at the some particular button than i can't find the button tags althoug i can find the button tags while touchupinside action.
- (void) loadImageInBackground:(NSArray *)urlAndTagReference {
NSLog(#"Received URL for tagID: %#", urlAndTagReference);
// Create a pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Retrieve the remote image. Retrieve the imgURL from the passed in array
NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];
UIImage *img = [[UIImage alloc] initWithData:imgData];
// Create an array with the URL and imageView tag to
// reference the correct imageView in background thread.
NSMutableArray *arr = [[NSArray alloc] initWithObjects:img, [urlAndTagReference objectAtIndex:1], nil ];
// Image retrieved, call main thread method to update image, passing it the downloaded UIImage
[self performSelectorOnMainThread:#selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
[pool release];
}
- (void) assignImageToImageView:(NSArray *)imgAndTagReference
{
// Create a pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;
UIButton *checkView;
// [imagesForCategories addObject:[imgAndTagReference objectAtIndex:1]];
// UITableViewCell *cell = [celebCategoryTableView cellForRowAtIndexPath:[imgAndTagReference objectAtIndex:1]];
// UIImageView *profilePic = (UIImageView *)[cell.contentView viewWithTag:20];
// profilePic.image = [imgAndTagReference objectAtIndex:0];
// checkView.tag = [[imgAndTagReference objectAtIndex:1] intValue];
// loop
for (UIButton *checkView in [self.tblImage subviews] )
{ i++;
NSLog(#"Checking tag: %d against passed in tag %d",checkView.tag, [[imgAndTagReference objectAtIndex:1] intValue]);
if ([checkView tag] == [[imgAndTagReference objectAtIndex:1] intValue]) {
if (i==35) break;
// Found imageView from tag, update with img
// [checkView setImage:[imgAndTagReference objectAtIndex:0]];
[checkView setImage:[imgAndTagReference objectAtIndex:0] forState:UIControlStateNormal];
//set contentMode to scale aspect to fit
checkView.contentMode = UIViewContentModeScaleAspectFit;
//change width of frame
CGRect frame = checkView.frame;
frame.size.width = 80;
checkView.frame = frame;
}
}
// release the pool
[pool release];
// Remove the activity indicator created in ViewDidLoad()
[self.activityIndicator removeFromSuperview];
}
the all code works perfect but i can't find the table cell subview here for (UIButton *checkView in [self.tblImage subviews] so how to find the subviews of table cell subviews.?
i want to create something like this pls see image.! after that new city will come and just section change the data will show new images in row and cell section.
you may use SDWebImage
Web Image
This library provides a category for UIImageVIew with support for remote images coming from the web.
It provides:
An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
Performances!
just use it
[youImageView setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageRetryFailed];
How do I access a previous view controller while in a subview? Because I'm able to perform actions but I'm just not able to use self.[my main view controller].
This is my code, for testing purposes:
PhotoViewController.m
-(IBAction)likeButton:(UIButton *)sender
{
//this part works
NSString *num = #"2";
self.label.text = [NSString stringWithFormat:#"%# + %#",
self.label.text,
num];
//this part doesn't work
//switch over to the third view to see if it worked
self.tabBarController.selectedIndex = 0;
}
I have a UITabBarController and one of its view controllers has a UIScrollView. Inside of the UIScrollView is a PhotoViewController object.
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
MyTabBarViewController *vc2 = [[MyTabBarViewController alloc] init];
SecondViewController *vc3 = [[SecondViewController alloc] init];
controller = [[DemoAppViewController alloc] init];
controller.view.frame = CGRectMake(0, 20, 320, 460);
controller.title = #"Intro Screen";
vc2.title = #"Explore";
vc3.title = #"Send a Pic";
UITabBarController *tbc = [[UITabBarController alloc] init];
tbc.viewControllers = [NSArray arrayWithObjects:controller, vc2, vc3, nil];
[controller release];
[vc2 release];
[vc3 release];
[self.window addSubview:tbc.view];
[self.window makeKeyAndVisible];
return YES;
}
Also, my TabBarViewController.m //not my actual UITabBarController though, wording is confusing
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
arrayCount = [array count];
scroller.delegate=self;
scroller.pagingEnabled=YES;
scroller.directionalLockEnabled=YES;
scroller.showsHorizontalScrollIndicator=NO;
scroller.showsVerticalScrollIndicator=NO;
//should have an array of photo objects and the number of objects, correct?
scrollWidth = 0;
scroller.contentSize=CGSizeMake(arrayCount*scroller.frame.size.width, scroller.frame.size.height);
for (int i = 0; i < arrayCount;i++) {
PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:#"PhotoViewController" bundle:nil];
UIImageView *scrollImageView = [[UIImageView alloc] initWithFrame:CGRectOffset(scroller.bounds, scrollWidth, 0)];
CGRect rect = scrollImageView.frame;
pvc.view.frame = rect;
pvc.label.textColor = [UIColor whiteColor];
id individualPhoto = [array objectAtIndex:i];
NSLog(#"%#",individualPhoto);
NSArray *keys=[individualPhoto allKeys];
NSLog(#"%#",keys);
NSString *imageURL=[individualPhoto objectForKey:#"source"];
NSURL *url = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
pvc.imageView.image = [[UIImage alloc] initWithData:data];
pvc.label.text = [individualPhoto objectForKey:#"id"];
[scroller addSubview:pvc.view];
[scrollImageView release];
//[pvc release];
scrollWidth += scroller.frame.size.width;
}
if (arrayCount > 3) {
pageControl.numberOfPages=3;
} else {
pageControl.numberOfPages=arrayCount;
}
pageControl.currentPage=0;
}
If a UIView subclass needs to message a controller above itself, a common (and often recommended?) way to do this is to have the view subclass implement the delegate protocol (a weak linked instance variable pointing to the view controller that you want to use). The view controller should then set itself as the delegate of the view when that view is being initialize.
Try defining this method in your PhotoViewController:
+ (YOURTABBARCONTROLLER*)parentTabBarController:(UIResponder*)view {
id nextResponder = nil;
id v = view;
while (nextResponder = [v nextResponder]) {
NSLog(#"Found Responder: %#", nextResponder); //-- ADDED THIS
if ([nextResponder isKindOfClass:[YOURTABBARCONTROLLER class]])
return nextResponder;
v = nextResponder;
}
return nil;
}
it will traverse the responder chain and return the first controller of a given type that is found. Replace YOURTABBARCONTROLLER with your actual tab bar controller class and you should be able to have:
-(IBAction)likeButton:(UIButton *)sender
{
//this part works
NSString *num = #"2";
self.label.text = [NSString stringWithFormat:#"%# + %#",
self.label.text,
num];
[PhotoViewController parentTabBarController:self.view].selectedIndex = 0;
// self.tabBarController.selectedIndex = 0;
}
Updated
-(IBAction)likeCommentButton:(UIButton *)sender
{
//code goes here
TypeSomethingViewController *typeSomethingViewController = [[TypeSomethingViewController alloc] init];
typeSomethingViewController.delegate = self;
[self presentModalViewController:typeSomethingViewController animated:YES];
[typeSomethingViewController release];
}
-(void)typeSomethingViewController:(TypeSomethingViewController *)controller didTypeSomething:(NSString *)text
{
//NSLog(#"response: %#", controller);
NSString *commentID = self.label.text;
for(UIViewController *controller in [PhotoViewController parentTabBarController:self.parentViewController.view].viewControllers)
{
if([controller isKindOfClass:[DemoAppViewController class]])
{
DemoAppViewController *davc = (DemoAppViewController *)controller;
//[davc commentPicture:commentID :message];
[davc likePicture:commentID];
}
}
[PhotoViewController parentTabBarController:self.view].selectedIndex = 0;
[self dismissModalViewControllerAnimated:YES];
}
Try this out to switch to the first controller.
self.tabBarController.selectedViewController
= [self.tabBarController.viewControllers objectAtIndex:0];
Change the index value to switch to whichever controller you want to switch to.
The tabBarController should be a property of the app delegate.
Try accessing it with :
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication]
delegate];
appDelegate.tabBarController.selectedIndex = 0;
Unless you declare the same property in PhotoViewController, you won't be able to access it this way.
Try importing the app delegate header in PhotoViewController.h like so :
#import "MyAppDelegate"
then try this code above replacing tabBarController by tbc which, as the example suggests is the name given to this property.
How can I set a TTStyledTextLabel inside of a UITableView.
Each TTStyledTextLabel contains Some parsed HTML.
Heres what I have I realize its probably completely wrong.
TTStyledTextLabel* label = [[TTStyledTextLabel alloc] autorelease];
cell.textLabel.text = [TTStyledText textFromXHTML:tempString lineBreaks:YES URLs:YES];
App Crashes on launch. I think its because I am setting the .text property with something that is not text. However, I don't know what else to set.
The following code will do what you want. Unfortunately, however, I cannot figure out how to automatically set the height. If memory isn't an issue you could keep a seperate array of TTStyledTextLabels and reference their heights.
in your loadView:
CGRect cgRct2 = CGRectMake(0, 35, 320, 375); //define size and position of view
tblView = [[UITableView alloc] initWithFrame:cgRct2 style:UITableViewStylePlain];
tblView.dataSource = [self constructDataSource];
tblView.delegate = self;
//[tblView reloadData];
[myView addSubview:tblView];
in your class:
-(TTListDataSource *)constructDataSource {
NSLog(#"constructDataSource");
NSMutableArray * namesArray = [[NSMutableArray alloc] init];
//ADD ITEMS
[namesArray addObject:[TTStyledText textFromXHTML:[NSString stringWithString:#"some XHTML"]]];
TTListDataSource * dataSource = [[TTListDataSource alloc] init];
for (int i = 0; i < [namesArray count]; i++) {
TTStyledText * text = [namesArray objectAtIndex:i];
[dataSource.items addObject:[TTTableStyledTextItem itemWithText:text]];
}
[namesArray release];
return dataSource;
}