UIView.Type 没有成员命名范围

UIView.Type does not have member named bounds

我只是想为视图的 bounds.size.width 和 .height 设置两个变量。

import UIKit

class BKView: UIView {

    var maxX: CGFloat = bounds.size.width
    var maxY: CGFloat = bounds.size.height

}

但是 Xcode 失败并显示错误:'BKView.Type' 没有名为 'bounds'.

的成员

有什么建议吗?

使用 self.bounds.size.widthself.bounds.size.height。您应该在初始化程序或其他一些函数中分配属性 maxXmaxY 值,而不是内联。示例:

init(frame: CGRect) {
    super.init(frame: frame)
    maxX = self.bounds.size.width
    maxY = self.bounds.size.height
}

这是一个措辞糟糕的编译器错误,但它的意思是您不能根据 class(或 superclass)的其他属性赋予属性默认值。这是正在发生的事情的一个更简单的变体:

class A {
    let x: Int

    init(x: Int) {
        self.x = x
    }
}

class B: A {
    // error: 'B.Type' does not have a member named 'x'
    let y = x
}

你必须在 init 方法中初始化 maxXmaxY,在你调用 super.init 之后(因为只有在那之后你才被允许访问超级class的属性)。

@Airspeed Velocity 给出了很好的解释。我想补充一点,或者您可以使用 lazy 初始化。例如:

class BKView: UIView {
    lazy var maxX: CGFloat = self.bounds.size.width
    lazy var maxY: CGFloat = self.bounds.size.height
}

有关详细信息,请参阅:http://mikebuss.com/2014/06/22/lazy-initialization-swift/

创建视图时,需要定义一些默认的初始化方法。定义一个class如下:

class TestView: UIView {

    var maxX : CGFloat?
    var maxY : CGFloat?

    override init() {

        super.init()
        initializeBounds()
    }

    required init(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        initializeBounds()

    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeBounds()
    }

    func initializeBounds()
    {
        maxX = self.bounds.size.width
        maxY = self.bounds.size.height

    }

    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code

        println("maxX: \(maxX!) maxY: \(maxY!)")
    }


}

每当 TestView 被 Storyboard 或 Coding 初始化时,TestView 的属性就会被初始化。

将视图添加到视图控制器的视图后,如下所示:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        var testView : TestView = TestView(frame: CGRectMake(10.0, 10.0, 100.0, 50.0))
        testView.backgroundColor = UIColor.redColor()
        self.view.addSubview(testView)

}

日志如下:

测试视图:maxX:100.0 maxY:50.0

为避免代码重复,initializeBounds()TestView 的初始值设定项中定义和调用: