2015-11-17 1 views
0

Я добавил UIScrollView из раскадровки и внутри этого прокрутки. У меня есть еще один UIView в виде контейнера. За UIScrollView у меня есть UIImageView тоже как родной брат. Это моя иерархия просмотра.Случай нажатия кнопки не срабатывает иногда для программно созданного UIButton

enter image description here

Теперь я добавляю Просмотров в этом виде контейнера программно.

-(void)setUI 
    { 
     int i; 
     for (i=0; i<[array count]; i++) { 

     NSLog(@"Object at index %i %@",i,[array objectAtIndex:i]); 

     UIView *view=[self GetAlertView:i]; 

    [self.contentView addSubview:view]; 
    float sizeOfContent = 0; 

    if (notY+viewParent.frame.size.height>self.contentView.frame.size.height) { 
     CGRect frame=self.contentView.frame; 
     frame.size.height=notY; 
     self.contentView.frame=frame; 
    } 



    self.mainScroll.contentSize = self.contentView.frame.size; 


} 

Вот как я генерирую виды.

-(UIView *)GetAlertView :(int)index 
    { 
     viewParent=[[UIView alloc] initWithFrame:CGRectMake(10, notY,  self.view.frame.size.width-20, 100)]; 
[viewParent setBackgroundColor:[UIColor clearColor]]; 
[viewParent setUserInteractionEnabled:YES]; 


UIImageView *backImage=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewParent.frame.size.width, viewParent.frame.size.height)]; 
[backImage setImage:[UIImage imageNamed:@"AlertBack"]]; 


//-------TITLE LABEL-------------- 

UILabel *lblTitle=[[UILabel alloc] initWithFrame:CGRectMake(20, 20, viewParent.frame.size.width-60, 30)]; 

[lblTitle setText:[[[array objectAtIndex:index] objectForKey:@"Info"] valueForKey:@"Headline"]]; 
[lblTitle setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15]]; 
[lblTitle setTextAlignment:NSTextAlignmentLeft]; 
[lblTitle setTextColor:[UIColor whiteColor]]; 

//-------ICON IMAGE------------ 

UIImageView *imgIco=[[UIImageView alloc] initWithFrame:CGRectMake(lblTitle.frame.origin.x+lblTitle.frame.size.width, 20, 30, 30)]; 

NSString *imgUrl=[[[[array objectAtIndex:index] objectForKey:@"Info"] objectForKey:@"Resource"] valueForKey:@"Uri"]; 
if([[array objectAtIndex:index] valueForKey:@"Realimg"]!=nil) 
{ 
    [imgIco setImage:[[array objectAtIndex:index] valueForKey:@"Realimg"]]; 
} 
else 
{ 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     NSURL *imageURL = [NSURL URLWithString:imgUrl]; 
     NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 
     UIImage *image = [UIImage imageWithData:imageData]; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      if(image!=nil){ 
       @try { 
        NSMutableDictionary *objectDict=[[NSMutableDictionary alloc] initWithDictionary:[[array objectAtIndex:index] mutableCopy]]; 
        [objectDict setObject:image forKey:@"Realimg"]; 
        [array replaceObjectAtIndex:index withObject:objectDict]; 

       } 
       @catch (NSException *exception) { 

       } 
       @finally { 

       } 

      } 

      [imgIco setImage:image]; 

     }); 
    }); 

} 


UILabel *lblMessage=[[UILabel alloc] initWithFrame:CGRectMake(20, lblTitle.frame.origin.y+lblTitle.frame.size.height+10, viewParent.frame.size.width-40, 10)]; 
[lblMessage setUserInteractionEnabled:NO]; 

[lblMessage setNumberOfLines:0]; 
CGSize maximumLabelSize = CGSizeMake(viewParent.frame.size.width-40, FLT_MAX); 
NSString *strDescript=[[[array objectAtIndex:index] objectForKey:@"Info"]valueForKey:@"Description"]; 


[lblMessage setText:strDescript]; 
[lblMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:14]]; 

CGSize expectedLabelSize = [strDescript sizeWithFont:lblMessage.font constrainedToSize:maximumLabelSize lineBreakMode:lblMessage.lineBreakMode]; 
//adjust the label the the new height. 
CGRect newFrame = lblMessage.frame; 
newFrame.size.height = expectedLabelSize.height; 
lblMessage.frame = newFrame; 
if (lblMessage.frame.size.height>10) { 
    float extendedH=lblMessage.frame.size.height-10; 


    CGRect newFrameMsg = viewParent.frame; 
    newFrameMsg.size.height = viewParent.frame.size.height+extendedH; 
    viewParent.frame = newFrameMsg; 

    CGRect newImgFrame=backImage.frame; 
    newImgFrame.size.height=backImage.frame.size.height+extendedH; 
    backImage.frame=newImgFrame; 

} 

[lblMessage setTextColor:[UIColor whiteColor]]; 

NSLog(@"Circle %lu",[[[[[array objectAtIndex:index] objectForKey:@"Info"] objectForKey:@"Area"] objectForKey:@"Circle"] count]); 
int circleCount=[[[[[array objectAtIndex:index] objectForKey:@"Info"] objectForKey:@"Area"] objectForKey:@"Circle"] count]; 

NSLog(@"Geocode %@",[[[[array objectAtIndex:index] objectForKey:@"Info"] objectForKey:@"Area"] objectForKey:@"Geocode"]); 
NSString *strGeoCod=[[[[array objectAtIndex:index] objectForKey:@"Info"] objectForKey:@"Area"] objectForKey:@"Geocode"]; 

NSLog(@"Polygon %lu",[[[[[array objectAtIndex:index] objectForKey:@"Info"] objectForKey:@"Area"] objectForKey:@"Polygon"] count]); 
int polygonCount=[[[[[array objectAtIndex:index] objectForKey:@"Info"] objectForKey:@"Area"] objectForKey:@"Polygon"] count]; 

UIImageView *imgEvac; 
UIButton *btnEvac; 


if (circleCount!=0 || [strGeoCod length]!=0 || polygonCount!=0) { 
    //----------EVACUATE IMAGE--------------- 
    imgEvac=[[UIImageView alloc] initWithFrame:CGRectMake(20, lblMessage.frame.origin.y+lblMessage.frame.size.height+5, 20, 30)]; 
    [imgEvac setUserInteractionEnabled:NO]; 
    imgEvac.animationImages=[NSArray arrayWithObjects:[UIImage imageNamed:@"Evac1"], 
          [UIImage imageNamed:@"Evac2"], 
          [UIImage imageNamed:@"Evac3"], 
          [UIImage imageNamed:@"Evac4"], 
          [UIImage imageNamed:@"Evac5"], 
          [UIImage imageNamed:@"Evac6"], 
          [UIImage imageNamed:@"Evac7"], 
          [UIImage imageNamed:@"Evac8"], 
          [UIImage imageNamed:@"Evac9"], 
          [UIImage imageNamed:@"Evac10"], 
          [UIImage imageNamed:@"Evac11"], 
          [UIImage imageNamed:@"Evac12"], 
          [UIImage imageNamed:@"Evac13"], 
          [UIImage imageNamed:@"Evac14"],nil]; 
    imgEvac.animationDuration = 1.0f; 
    imgEvac.animationRepeatCount = 0; 
    [imgEvac startAnimating]; 



    //----------EVACUATE BUTTON------------- 
    btnEvac=[UIButton buttonWithType:UIButtonTypeCustom] ; 
    [btnEvac setTitle:@"Evacuate" forState:UIControlStateNormal]; 
    [btnEvac setTitleColor:[UIColor greenColor] forState:UIControlStateNormal]; 
    [btnEvac addTarget:self action:@selector(EvacuateClick:) forControlEvents:UIControlEventTouchUpInside]; 

    btnEvac.frame=CGRectMake(imgEvac.frame.origin.x+imgEvac.frame.size.width+5, lblMessage.frame.origin.y+lblMessage.frame.size.height+5, 75, 30); 






    intlbldateX=btnEvac.frame.origin.x+btnEvac.frame.size.width; 

}

else 
{ 
    intlbldateX=20; 
} 





//----------DATE LABEL------------------ 
UILabel *lblDate=[[UILabel alloc] initWithFrame:CGRectMake(intlbldateX, lblMessage.frame.origin.y+lblMessage.frame.size.height+5, viewParent.frame.size.width-(intlbldateX+10), 30)]; 
[lblDate setUserInteractionEnabled:NO]; 
[lblDate setBackgroundColor:[UIColor redColor]]; 
[lblDate setText:[[array objectAtIndex:index]valueForKey:@"Sent"]]; 
[lblDate setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15]]; 
[lblDate setTextAlignment:NSTextAlignmentRight]; 
[lblDate setTextColor:[UIColor whiteColor]]; 

CGRect newFrame2=viewParent.frame; 
newFrame2.size.height=viewParent.frame.size.height+10; 
viewParent.frame=newFrame2; 

CGRect newImgFrame2=backImage.frame; 
newImgFrame2.size.height=backImage.frame.size.height+10; 
backImage.frame=newImgFrame2; 

// --------- Verticle ЛИНИЯ --------------

UIView *vwVerticle=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, viewParent.frame.size.height)]; 
[vwVerticle setUserInteractionEnabled:NO]; 
[vwVerticle setBackgroundColor:[self colorWithHexString:[[[[[array objectAtIndex:index]objectForKey:@"Info"] objectForKey:@"Resource"] valueForKey:@"ColorCode"] stringByReplacingOccurrencesOfString:@"#" withString:@""]]]; 

[viewParent addSubview:backImage]; 
[viewParent addSubview:lblTitle]; 
[viewParent addSubview:imgIco]; 
[viewParent addSubview:lblMessage]; 
[viewParent addSubview:imgEvac]; 

[viewParent addSubview:lblDate]; 
[viewParent addSubview:vwVerticle]; 
[viewParent addSubview:btnEvac]; 


notY=viewParent.frame.origin.y+viewParent.frame.size.height+20; 


return viewParent; 

}

Но моя проблема заключается в том, что btnEvac не доступен для просмотра. Но иногда я могу щелкнуть его только один раз. Это мое событие нажатия кнопки.

-(IBAction)EvacuateClick :(UIButton *)sender 
    { 
    NSLog(@"Evacuate clicked"); 
    } 

Иногда это срабатывает в первый раз. После этого ничего не происходит. Я не знаю, в чем причина. Я установил взаимодействие с пользователем enabled = YES с моим видом прокрутки и контейнером. но не к представлению всплеска изображения. Надеюсь, я тоже этого не хочу. Пожалуйста, помогите мне.

Благодаря

Это, как я загружаю больше вид на нижнюю

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
float bottomEdge = self.mainScroll.contentOffset.y + self.mainScroll.frame.size.height; 
if (bottomEdge >= self.mainScroll.contentSize.height) { 
    // we are at the end 

    //[self performSelectorInBackground:@selector(callscrol) withObject:nil]; 
    [self callscrol]; 
} 

}

-(void)callscrol 

{

if(!loading&& !resNull) 
{ 
    float offs = (self.mainScroll.contentOffset.y+self.mainScroll.bounds.size.height); 
    float val = (self.mainScroll.contentSize.height); 
    if (offs==val) 
    { 
     loading=YES; 
     start_rec+=1; 

     [self performSelectorInBackground:@selector(LoadData) withObject:nil]; 

    } 
} 

}

И получить больше данных с сервера

-(void)LoadData 

{

[self.actind startAnimating]; 
[self.actind setHidden:NO]; 
loading=YES; 

NSString *serverURL = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"BaseURL"]; 
NSString *queryString=[NSString stringWithFormat:@"GetDisasterAlertsJson?authCode=%@&lastUpdated=%@&version=%@&langId=%@&pageNo=%@&noOfMessages=%@",dm.strAuthCode,lastUpdate,@"1.0",@"1",[NSString stringWithFormat:@"%i",start_rec],@"5"]; 
NSString *urlString=[NSString stringWithFormat:@"%@%@",serverURL,queryString]; 
// Create the request. 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; 
// Create url connection and fire request 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
    if (!data) { 
     NSLog(@"%s: sendAynchronousRequest error: %@", __FUNCTION__, connectionError); 
     return; 
    } else if ([response isKindOfClass:[NSHTTPURLResponse class]]) { 
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; 
     if (statusCode != 200) { 
      NSLog(@"%s: sendAsynchronousRequest status code != 200: response = %@", __FUNCTION__, response); 
      return; 
     } 
    } 

    NSError *parseError = nil; 
    NSData *dataXMLRemoved=[self ReplaceXMLData:data]; 
    NSLog(@"======= Data XML Removed ======== %@",dataXMLRemoved); 
    dictionary = [NSJSONSerialization JSONObjectWithData:dataXMLRemoved options:NSJSONReadingAllowFragments error:&parseError]; 

    if (!dictionary) { 
     NSLog(@"%s: JSONObjectWithData error: %@; data = %@", __FUNCTION__, parseError, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); 
     resNull=NO; 
     return; 
    } 


    // now you can use your `dictionary` object 

    else 
    { 
     NSLog(@"JSON Dictionary================ %@",dictionary); 
     array=[dictionary objectForKey:@"Cmessage"]; 
     NSLog(@"Array ####### %@",array); 
     resNull=NO; 
     loading=NO; 
     [self.actind stopAnimating]; 
     [self.actind setHidden:YES]; 
     [self setUI]; 


    } 
}]; 

}

+0

похоже, что он не работает после того, как загрузите больше изображений снизу – user1960169

ответ

0

я не уверен, если это ваша проблема, но по умолчанию UIScrollViews задержка прикасается от фильтрация до встроенных представлений для прокрутки. Это может показаться, что кнопки не запускаются каждый раз, когда на самом деле это занимает около секунды для срабатывания сенсорного события во встроенном виде.

Попробуйте отключить эту настройку на вашем прокрутке.

self.mainScroll.delaysContentTouches = NO; 
+0

Но тогда его нельзя прокручивать. – user1960169

+0

И ни одна кнопка не может быть нажата, после того как я установил ее в НЕТ. В моем случае я могу кликнуть до 3-го бита, и остальные вещи не будут доступны. Подобные кнопки, расположенные ниже длины экрана, не могут быть изменены. Но если обновление произошло, снова эти кнопки становятся доступными, но только 3 или 4, а остальные кнопки не работают – user1960169

Смежные вопросы