简体   繁体   中英

setting Alpha for UIView that is a subview of UIScrollVIew very slow

I have UIScrollView that contains several UIView when I try to setAlpha: for one of the UIView , I get 1.5 second delay till the UIView alpha is set.

Here is the code below setContentOffset does run before the setAlpha: although the setAlpha: is written before in code

-(void)setAlphaForIndex:(int)Index{

    for (UIView *v in imgScroll.subviews){

        if (v.tag == Index) {
            [v setAlpha:0.6];
            if (![self checkIfImageInScrollRange:Index]){
                if (v.tag < 5)
                    [imgScroll setContentOffset:CGPointMake(0, 0) animated:YES];
                else
                    [imgScroll setContentOffset:CGPointMake((Index - 5) * (CELLWIDTH) + (Index - 5 - 1) * 3, 0) animated:YES];
            }
        } else {
            [v setAlpha:1.0];
        }
    }
}

Went trough your code again.

It looks like you could use the loop only for setting alpha and set the contentOffset later.

Code would be this:

-(void)setAlphaForIndex:(int)Index {

    for (UIView *v in imgScroll.subviews) {

        if (v.tag == Index) 
            [v setAlpha:0.6];
        else
            [v setAlpha:1.0];
    }

    if (![self checkIfImageInScrollRange:Index]){
      if (Index < 5)
        [imgScroll setContentOffset:CGPointMake(0, 0) animated:YES];
      else
        [imgScroll setContentOffset:CGPointMake((Index - 5) * (CELLWIDTH) + (Index - 5 - 1) * 3, 0) animated:YES];
    }
}

Since there is always only one view with alpha 0.6 you can avoid the loop and improve performance.

Add an integer property called transparentViewIndex and initialize it to -1. Improved code would then look like:

-(void)setAlphaForIndex:(int)Index{

  if (self.transparentViewIndex > -1) [[imgScroll viewWithTag: transparentViewIndex] setAlpha:1.0];

  [[imgScroll viewWithTag: Index] setAlpha:0.6];

  self.transparentViewIndex = Index;

  if (![self checkIfImageInScrollRange:Index]){
    if (Index < 5)
      [imgScroll setContentOffset:CGPointMake(0, 0) animated:YES];
    else
      [imgScroll setContentOffset:CGPointMake((Index - 5) * (CELLWIDTH) + (Index - 5 - 1) * 3, 0) animated:YES];
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM