this tutorial/code by Matt Coneybeare 나는이 질문에 대한 기존의 답을 찾았지만 만족하지 않았다 참조하십시오. 코드를 적게 사용하고 메서드를 재정의 할 필요가 없으며 모든 뷰에 적용 할 수있는 대체 방법이 있습니다. 이 아이디어는 UIView
의 하위 레이어에 CAGradientLayer
을 하위 레이어로 추가하는 것입니다. 이 접근법이 어디에서나 문서화되어있어 공유하고 싶지 않았습니다. 다음과 같이
는 CAGradientLayer
어떤 UIView
에 추가
UIView
헤더 카테고리 - UIView의 + Gradient.h :
#import <UIKit/UIKit.h>
@interface UIView (Gradient)
-(void) addLinearUniformGradient:(NSArray *)stopColors;
@end
카테고리 UIView
구현하여 UIView + Gradient.m에 :
#import "UIView+Gradient.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIView (Gradient)
-(void) addLinearUniformGradient:(NSArray *)stopColors
{
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.bounds;
gradient.colors = stopColors;
gradient.startPoint = CGPointMake(0.5f, 0.0f);
gradient.endPoint = CGPointMake(0.5f, 1.0f);
[self.layer addSublayer:gradient];
}
@end
그라데이션을 설정하는 방법 UITableViewCell
의 backgroundView after crea 팅 UITableViewCell
:
// Set the gradient for the cell's background
CGRect backgroundViewFrame = cell.contentView.frame;
backgroundViewFrame.size.height = yourCellHeight;
cell.backgroundView = [[UIView alloc] initWithFrame:backgroundViewFrame];
[cell.backgroundView addLinearUniformGradient:[NSArray arrayWithObjects:
(id)[[UIColor redColor] CGColor],
(id)[[UIColor greenColor] CGColor], nil]];
이 예에서는이 방법 (일정 간격) 설정 단순한 2 정지 구배에 나타냈다. CAGradientLayer
설명서를 간략히 살펴보면 더 복잡한 그래디언트를 설정하는 방법을 보여줍니다.
(* 추가 중요 정보 * 편집)
한 가지 유념해야 할 추가 것은 당신이있는 tableView 같은 방법으로 그라디언트 레이어를 추가하는 경우이다 : cellForRowAtIndexPath의 UITableViewCells 일반적인 존재에 재사용 (즉, [tableView dequeueReusableCellWithIdentifier : @ "foo"]). 셀을 다시 사용하기 때문에 셀이 대기열에서 제외 될 때마다 항상 테이블보기 셀에 그래디언트 레이어를 추가하면 셀 수명 동안 여러 개의 그래디언트 레이어가 테이블 뷰 셀에 추가 될 수 있습니다. 이는 성능 저하의 원인이 될 수 있습니다. 이 문제는 가시적 인 결과가 변경되지 않고 발생할 수 있으므로 감지/관찰하기가 어려울 수 있습니다. 이 문제를 해결할 수있는 몇 가지 방법이 있지만 CAGradientLayer를 추가하는 것 외에 위의 원래 코드를 수정하여 생성 된 CAGradientLayer를 호출자에게 반환하는 방법을 고려해야합니다. 그리고 실제로보기에 포함되는 경우 그라디언트 레이어를 제거 할 수 있습니다 다른 카테고리 방법 작성하는 매우 간단하다 : 그라데이션을 제거
이
-(BOOL) removeGradient:(CAGradientLayer *)gradientLayer
{
// Search for gradient layer and remove it
NSArray *layers = [self.layer sublayers];
for (id layer in layers) {
if (layer == gradientLayer) {
[gradientLayer removeFromSuperlayer];
return YES;
}
}
// Failed to find the gradient layer in this view
return NO;
}
모든 사용 사례 필요하지 않습니다,하지만 사용 사례의 경우 셀 재사용 결과가 나타나면 그라디언트를 제거하는 것이 좋습니다. 이 메소드를 호출하는 것을 고려해야 할 곳은 UITableViewCell의 prepareForReuse 메소드이다.
원본 솔루션이이 문제를 해결하지 못해서 죄송합니다. 그러나 그것은 매우 미묘 할 수있는 것이기 때문에이 추가 정보로 나의 대답을 업데이트하고 싶었습니다.
이것이 유일한 방법이라고 생각합니다. – tadejsv
높이가 같은 크기가 아닌 경우 어떻게해야합니까?백그라운드 그래픽을 만들려면 어떻게해야합니까? –