【问题标题】:how to call drawrect in UIView variable in a subclass of UIView?如何在 UIView 的子类中调用 UIView 变量中的 drawrect?
【发布时间】:2012-10-24 17:38:44
【问题描述】:

我创建了一个 UIView 的子类,在这个类中我声明了一个 UIView 变量。 我想调用我的 UIView 变量的 DrawRect,因为现在当我调用 DrawRect 时,它会绘制我的 UIView 类,而不是 UIView 变量,我该怎么做?

抱歉我的英语不好。

【问题讨论】:

    标签: iphone uiview drawrect


    【解决方案1】:

    您不调用drawRect,而是在您的子视图上调用setNeedsDisplay

    【讨论】:

    • 假设您有UIView *subview1,它是mainView 的子视图。在这种情况下,每当您需要重绘subview1 时,您都可以在mainView 的实现中调用[subview1 setNeedsDisplay]。鉴于您的 subview1 实现已覆盖 -(void)drawRect:(CGRect)rect 方法,它将被调用。
    【解决方案2】:

    您有一个 UIViewCustomClass ,其中还有一个 UIView ?像这样:

    @interface MyView : UIView
    {
      AnotherView *aView;
    }
    

    对吗?

    因此,如果您想重绘“aView”变量,您必须覆盖 MyView 类中的 setNeedsDisplay 方法:

    .h

    @interface MyView : UIView
    {
          AnotherView *aView;
    }
    
    - (void)setNeedsDisplay;
    -(void) drawRect:(CGRect) r;
    
    @end
    

    .m

    @implementation MyView
    
    - (void)setNeedsDisplay
    {
      [super setNeedsDisplay];
      [aView setNeedsDisplay];
    }
    
    -(void) drawRect:(CGRect) rect
    {
      //Do your own custom drawing for the current view
    }
    
    @end
    

    编辑: 在这里,aView 也是一个自定义类(AnotherView 的类型),因此您可以像我们之前对 MyViewClass 所做的那样覆盖 draw rect 方法:

    在另一个视图.m 中:

    @implemetation AnotherView
    
    -(void) drawRect:(CGRect) rect
    {
      //Do drawing for your aView variable ;)
    }
    
    @end
    

    根据苹果指南,你不应该直接调用 drawRect (cf documentation)

    【讨论】:

    • 谢谢,但是我如何在我的 UIView 变量上绘图?我的意思是如何在我的 UIView 变量上绘制一条线?
    • 您还需要对变量进行子类化并覆盖 drawRect 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多