CGGradient不可见(不使用界面构建器),并且无法触发UIButtons

时间:2011-04-25 12:37:19

标签: xcode uiview uiviewcontroller uibutton

我创建了一个包含CGGradient的视图:

// Bar ContextRef
CGRect bar = CGRectMake(0, screenHeight-staffAlignment, screenWidth, barWidth);
CGContextRef barContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(barContext);
CGContextClipToRect(barContext,bar);    

// Bar GradientRef
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[16] = { 1.0,1.0,1.0,0.0, 0.0,0.0,0.0,1.0, 0.0,0.0,0.0,1.0, 1.0,1.0,1.0,0.0}; 
CGFloat locations[4] = {0.95,0.85,0.15,0.05};
size_t count = 4;
CGGradientRef gradientRef = CGGradientCreateWithColorComponents(colorSpace, components, locations, count);

// Draw Bar
CGPoint startPoint = {0.0,0.0};
CGPoint endPoint = {screenWidth,0.0};
CGContextDrawLinearGradient(barContext, gradientRef, startPoint, endPoint, 0);
CGContextRestoreGState(barContext);     

此代码在UIView的drawRect方法中调用。然后我使用UIViewController访问创建的视图。

- (void)loadView {

MainPageView *mpView = [[MainPageView alloc] initWithFrame:[window bounds]];
[self setView:mpView];
[mpView release];

}

并通过appDelegate显示在屏幕上:

mpViewController = [[MainPageViewController alloc] init];   
[window addSubview:[mpViewController view]];

[window makeKeyAndVisible];

UIView包含更多可见的对象,例如UIButtons。我假设因为它们被添加为子视图。但我无法弄清楚如何将CGGradient添加为子视图?它需要吗? CGGradient不可见还有另一个原因吗?

我也没有获得UIButtons的功能。我想这是因为我已经将UIButtons添加到视图中。是否需要在UIViewController或appDelegate中添加按钮以具有功能。很抱歉,问一下看似简单的问题,但我试图在没有Interface Builder的情况下完成编程,而且这些材料很少。如果有人能指出我在这两个问题上的正确方向,我将非常感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

按钮上的功能丢失了,因为框架太大但按钮仍然可见,因为背景是clearColor