setting Alpha for UIView that is a subview of UISc

2019-09-17 11:44发布

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];
        }
    }
}

1条回答
孤傲高冷的网名
2楼-- · 2019-09-17 12:32

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];
  }
}
查看更多
登录 后发表回答