这是一个例子: 在多个按钮上显示多个图像并在滚动视图上显示
(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 :(得分:0)
您的代码存在的问题是您没有加载任何内容。我假设您要从Internet下载图像,然后在滚动视图上显示它。为此,您必须使用NSURLRequest
和NSURLConnection
。
请查看Apple的文档https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html和https://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?