我刚开始玩Xcode 4.3中的Master-Detail视图模板,我正在尝试更改master的背景颜色并将其设置为颜色渐变。 这是我试过的:
Colors.m
#import "Colors.h"
@implementation Colors
+ (UIColor *) navigationMenuGradientTop
{
return [UIColor colorWithRed:213.0f/255.0f green:91.0f/255.0f blue:92.0f/255.0f alpha:1.0f];
}
+ (UIColor *) navigationMenuGradientBottom
{
return [UIColor colorWithRed:188.0f/255.0f green:0.0f/255.0f blue:1.0f/255.0f alpha:1.0f];
}
+ (CAGradientLayer *) navigationMenuGradient
{
NSArray *colors = [NSArray arrayWithObjects:(id)self.navigationMenuGradientTop, self.navigationMenuGradientBottom, nil];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = colors;
return gradientLayer;
}
@end
MasterViewController.m
import "Colors.h"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
CAGradientLayer *bgLayer = [Colors navigationMenuGradient];
bgLayer.frame = tableView.bounds;
[tableView.layer insertSublayer:bgLayer atIndex:0];
return cell;
}
运行后,我在main
- Thread 1: EXC_BAD_ACCESS (code=1, address=0xxxxxxxx)
int main(int argc, char *argv[])
{
@autorelasespool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
我也将QuartzCore框架添加到项目中。我在这里错过了什么?当发生此类错误时,我通常应该选择哪个方向(因为构建成功,应用程序似乎已经崩溃了)?
答案 0 :(得分:22)
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
来自:Gradients on UIView and UILabels On iPhone
此代码可以帮助您解决问题。
答案 1 :(得分:2)
为了向视图添加背景渐变,我按照此链接中的教程进行了操作:
http://danielbeard.wordpress.com/2012/02/25/gradient-background-for-uiview-in-ios/
在我的情况下,我有一个UITableView,并希望渐变在背景中。当我在链接中使用下面的代码时,我的tableview消失了。
-(void) ViewWillAppear:(BOOL) animated {
CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];
}
在如下修改我的代码时,可以同时拥有背景渐变和桌面视图。
-(void) ViewDidAppear:(BOOL) animated {
CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.tableView.layer insertSublayer:bgLayer atIndex:0];
}
答案 2 :(得分:0)
http://danielbeard.wordpress.com/2012/02/25/gradient-background-for-uiview-in-ios/