到目前为止,我的代码正在运行,但我必须为 UIView
创建一个类.这有点不方便,因为我也需要与 ViewController 交互。
顺便说一句,我确实尝试过 [self setNeedsDisplay]
在 ViewDidLoad
的UIViewController
子类文件,但它没有工作。
这是代码,适用于 UIView
子类但未在 UIViewController
上调用一:
- (void)drawRect:(CGRect)rect
{
UIColor *currentColor = [UIColor redColor];
CGContextRef context = UIGraphicsGetCurrentContext();
someNum = 1;
CGContextBeginPath(context);
CGContextMoveToPoint(context, 30, 40);
[self addDotImageX:30 andY:40];
CGContextSetLineWidth(context, 2);
CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
CGContextStrokePath(context);
}
关于尝试什么的任何想法?顺便说一句,这是一个 TabBar 应用程序。我知道那些会以某种方式阻止对
drawRect
的调用.以编程方式创建的选项卡,而不是通过 Nib 。例如:
NSMutableArray *listOfViewControllers = [[NSMutableArray alloc] init];
UIViewController *vc;
vc = [[Education alloc] init];
vc.title = @"Education";
[listOfViewControllers addObject:vc];
vc.tabBarItem.image = [UIImage imageNamed:@"info.png"];
[vc release];
我会很感激任何想法。我已经浏览了本网站上与
setNeedsDisplay
相关的答案不打电话 drawRect
并没有为我的特殊情况找到答案。谢谢。
最佳答案
你把两个类(class)混在一起了。 UIViewController 不是 UIView,这意味着它不继承自 UIView。但好消息是has a view, declared as property : 组成。 drawRect 方法仅在 UIView 类/子类中可用。
如果您想强制 Controller 的 View 重绘,您可以调用
[self.view setNeedsDisplay];
在 View Controller 中。
您可以使用 loadView 将自己的自定义 View 设置为 viewController 的 View 。方法。它可能看起来像这样:
- (void)loadView
{
MySubclassOfUIView *rootView = [[MySubclassOfUIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// do more view configuration ...
self.view = rootView;
[rootView release];
}
因此,您可以在 MySubclassOFUIView.m 文件中将绘图代码分开。
关于 UIViewController :
The UIViewController class provides the fundamental view-management model for iPhone applications. The basic view controller class supports the presentation of an associated view, support for managing modal views, and support for rotating views in response to device orientation changes.
和 的目的UIView :
The UIView class defines a rectangular area on the screen and the interfaces for managing the content in that area. At runtime, a view object handles the rendering of any content in its area and also handles any interactions with that content.
看看Cocoa Core Competencies / Model-View-Controller在 Apple 的官方文档中,它描述了 MVC 设计模式。
关于objective-c - drawRect 在 UIView 子类上被调用,但不在 UIViewController 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5970512/