我在动态添加UIButtons与背景图像作为UIScrollView的子视图时遇到了问题。它是一种在scrollView上使用UIButton的图像库。我已经使用这种方法来处理我的几个应用程序,它对静态内容的工作很好。 但是这一次,Im从Web服务加载图像并保存到文档目录,然后调用该方法创建图库。逻辑与我的其他应用程序相同。但我无法弄清楚这里有什么问题。 我会把这里的代码一个是检索数据和其他是创建画廊。UIScrollView动态内容不出现
数据从服务器检索
-(void)loadDataFromServer{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
arrCats = [[NSMutableArray alloc]init];
arrPromos = [[NSMutableArray alloc]init];
//[spinMenu startAnimating];
// load promo images from the server
for(int i=0;i<[arrPromos count];i++)
{
NSString *urlString = [Constants getImages:[[arrPromos objectAtIndex:i] objectForKey:@"image"]];
NSLog(@"Get Images API Call : %@", urlString);
NSURL *imageurl = [NSURL URLWithString:urlString];
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageurl];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
if(imageData != nil){
// save the images temporally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:[[arrPromos objectAtIndex:i] objectForKey:@"image"]]; //Add the file name
[imageData writeToFile:filePath atomically:YES];
}
});
});
}
// Load promotions from server
dispatch_async(queue, ^{
NSLog(@"Promotions Loading Started");
NSString *urlString = [Constants getAllPromotions:@"GetPromo.php"];
NSLog(@"Get Promotions API Call : %@", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Specify that it will be a GET request
request.HTTPMethod = @"GET";
[request setHTTPShouldHandleCookies:NO];
NSURLResponse *responseURL;
NSError *error;
NSData *dataPromotions = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseURL error:&error];
if (responseURL == nil)
{
// Check for problems
if (error != nil)
{
NSLog(@"Get Promtions Connection failed! Error - %@", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Error!" message:@"Promotions data failed to load!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
NSString *responseString = nil;
responseString = [[NSString alloc] initWithData:dataPromotions encoding:NSUTF8StringEncoding];
if ([responseString rangeOfString:@"error"].location == NSNotFound)
{
NSDictionary *response = [[NSDictionary alloc] init];
response = (NSDictionary *)[responseString JSONValue];
NSLog(@"Response : Promotions %@", response);
if(response != Nil){
if([response count]>0){
arrPromos = [NSMutableArray arrayWithArray:[response objectForKey:@"Promos"]];
NSLog(@"ArrPromos @ loading %@", arrPromos);
// create promos galley
[self createPromosGallery];
}
}
}
}
});
注:[自createPromosGallery];在下载完所有图像和数据后调用。
创建画廊
-(void) createPromosGallery{
// sort arrPromos based on priority
for(int i=0; i<[arrPromos count];i++){
[arrPromos sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
NSString *string1;
NSString *string2;
if(![[dict1 objectForKey:@"priority"] isKindOfClass: [NSNull class]])
string1 = [dict1 objectForKey:@"priority"];
if(![[dict2 objectForKey:@"priority"] isKindOfClass: [NSNull class]])
string2 = [dict2 objectForKey:@"priority"];
return [string1 compare:string2 options:NSNumericSearch];
}];
}
NSLog(@"ArrPromos %@", arrPromos);
// scrollView size
CGFloat screenHieght = [UIScreen mainScreen].bounds.size.height;
if(screenHieght>500){
scrollView.frame = CGRectMake(0, 0, 320, 568);
}
else{
scrollView.frame = CGRectMake(0, 0, 320, 480);
}
// define scrollview height
int scrollHieght;
scrollHieght = ([arrPromos count]-1)/2;
NSLog(@"Scroll height %d",scrollHieght);
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width , scrollHieght * 160 +200);
scrollView.pagingEnabled = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
scrollView.delegate = self;
for(int i=0;i<[arrPromos count];i++)
{
float x;
float y;
if(i%2==0)
{
x=30.0;
y=(i/2)*160+25;
}
if(i%2==1) {
x=170.0;
y=(i/2)*160+25;
}
// retreive saved images
NSString *strImgName;
UIImage *buttonUpImage;
// create buttons
button = [UIButton buttonWithType:UIButtonTypeCustom];
strImgName = [[arrPromos objectAtIndex:i] objectForKey:@"image"];
NSLog(@"Button image name %@", strImgName);
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@",docDirectory,strImgName];
buttonUpImage = [UIImage imageWithContentsOfFile:filePath];
[button setBackgroundImage:buttonUpImage forState:UIControlStateNormal];
button.frame = CGRectMake(x, y, 120,140);
[button setTag:i];
[button addTarget:self action:@selector(promoBtnPressed:)forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
}
}
注:我在两个iOS的7和6的iOS 7测试,它需要很长的时间来滚动视图显示的图像(目前只有2图片)。否则,如果我在scroolView上点击,则会出现图像。
在iOS 6中,没有出现
感谢答案。但我认为,这里不可能是这种情况。因为,如果触摸scrollView,内容会很快出现。而且,在iOS 6中似乎没有任何东西出现(按钮背景图像)。但是,如果我点击按钮,它会触发。这意味着正确创建了滚动视图内容,但是如果我不触摸scrollView,它们不会出现。 – sajaz