2012-09-19 54 views
1

下面是一个例子: 显示多按钮多图像,并显示在滚动视图如何显示从按钮上的URL加载的图像?

(void)viewDidLoad 
    { 
[super viewDidLoad]; 
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
InitData *inData=[[InitData alloc]init]; 


scrollview.delegate=self; 
scrollview.scrollEnabled = YES; 
int scrollWidth = 120; 
scrollview.contentSize = CGSizeMake(scrollWidth,100); 


int xOffset = 0; 
//imageView.image = [UIImage imageNamed:[imagesName objectAtIndex:0]]; 

//Test 
NSURL *url=[NSURL URLWithString:@"....."]; 
NSData *jsonData=[NSData dataWithContentsOfURL:url]; 


if (jsonData !=nil) 
{ 

     NSError *error=nil; 
     id result=[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; 

     if (error ==nil) 
     { 
       NSLog(@"%@",result); 
       // NSMutableArray *ArImg = nil; 
       NSArray* rus=[result objectForKey:@"RespOBJ"]; 

    for (int index = 0; index < rus.count ; index++) 
    { 
     NSMutableDictionary* final=[rus objectAtIndex:index]; 

     [inData setId:(int)[final objectForKey:@"Id"]]; 
     [inData setTum:[final objectForKey:@"TumbImage"]]; 
     [inData setImage:[final objectForKey:@"Image"]]; 

     UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; 
     [btn setImage:[UIImage imageNamed:[inData getImage]] forState:(UIControlStateNormal)]; 
     //[btn setImage:[UIImage imageWithData:jsonData] forState:(UIControlStateNormal)]; 

     [btn setTag:index]; 
     btn.bounds = CGRectMake(10, 10, 50, 50); 
     btn.frame = CGRectMake(5+xOffset, 0, 160, 70); 

     scrollview.contentSize = CGSizeMake(scrollWidth+xOffset,70); 

     NSLog(@"%@",[inData getId]); 
     NSLog(@"%@",[inData getImage]); 
     NSLog(@"%@",[inData getTum]); 

     [btn addTarget:self 
      action: @selector(btnclick:) 
      forControlEvents: UIControlEventTouchDown]; 

    [scrollview addSubview:btn]; 

    xOffset += 170; 

}

+0

而这个问题......?你的代码的结果是什么? –

+1

结果通过使用NSLog的...但在用户界面scrollview是空的 – Azar

+0

你想设置你的按钮像照片画廊? – TheTiger

回答

0

与您的代码的问题是,你不加载任何东西。我假设你想从互联网下载图像,然后在滚动视图上显示它。为此,您必须使用NSURLRequestNSURLConnection。 看一看苹果的文档https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.htmlhttps://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
你也可以像如何加载数据异步Object-c/iOS :How to use ASynchronous to get a data from URL?

+1

,但我可以从网址获取数据..但我可以在scrollview中显示数据..你了解我吗? – Azar

+0

好吧,那么你如何将数据存储在InitData对象中?我看到你设置图像'[inData setImage:[final objectForKey:@“Image”]]; ',但它是一个链接?一些数据 ?不管它是什么,你都不能使用'[UIImage imageNamed:]'方法来加载它!试试'[UIImage imageWithData:]' – nicolasthenoz