【问题标题】:Programmatically calling drawRect() in swift以编程方式快速调用 drawRect()
【发布时间】:2016-02-21 04:22:34
【问题描述】:

我对 swift 还很陌生,而且我一直以编程方式完成所有编码。我终于开始拓展业务,开始使用 Interface Builder 学习一些很棒的东西。

我在使用 drawRect(rect: CGRect) 函数创建的 UIView 类中创建了一些很酷的自定义绘图,现在我希望能够在循环中多次调用该类以在我的视图中进行布局。每当我尝试以编程方式实例化视图时,似乎 drawRect 没有被调用。我没有收到任何错误,只是没有绘制任何内容。 这是我用于布置自定义视图的代码,其中 TesterView 是我执行自定义绘图的自定义 UIView 子类:

func testView() {

    let testerView:TesterView = TesterView()
    self.view.addSubview(testerView)
    testerView.translatesAutoresizingMaskIntoConstraints = false
    let height = NSLayoutConstraint(item: testerView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 200)
    let width = NSLayoutConstraint(item: testerView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 200)
    let centerX = NSLayoutConstraint(item: testerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
    let bottom = NSLayoutConstraint(item: testerView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
    self.view.addConstraints([height, width, centerX, bottom])


}

我们将不胜感激任何和所有的帮助。我还没有开始尝试循环调用视图,因为我什至无法让它工作一次。我最终需要做的是循环并多次实例化该类。

【问题讨论】:

    标签: ios iphone xcode swift drawrect


    【解决方案1】:

    您没有明确调用drawRect:。相反,您将needsDisplay 属性设置为YES

    来自View Programming Guide: Creating a custom view

    导致视图重新显示的最常见方法是告诉它其图像无效。 [...]NSView 定义了两种将视图图像标记为无效的方法:setNeedsDisplay:,使视图的整个边界矩形无效;setNeedsDisplayInRect:,使视图的一部分无效。

    来自UIView Class Reference

    当您的视图的实际内容发生变化时,您有责任通知系统您的视图需要重绘。为此,您可以调用视图的 setNeedsDisplaysetNeedsDisplayInRect: 方法。

    - (void)drawRect:(CGRect)rect
    [...]
    你永远不应该自己直接调用这个方法。要使视图的一部分无效,从而导致该部分被重绘,请改为调用 setNeedsDisplaysetNeedsDisplayInRect: 方法。

    您在drawRect: 中实现绘图,然后在需要重绘视图时调用[myView setNeedsDisplay:YES](例如,对于游戏,在循环中)。

    【讨论】:

    • 非常感谢!我不知道为什么我对自己如此苛刻,或者为什么我自己似乎无法找到原来如此简单的答案!我是这个社区的新手,但它已证明自己是一种宝贵的资源。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2016-07-27
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多