这是我的RectangleView:

import UIKit

class RectangleView: UIView
{
    init(frame: CGRect)
    {
        // Initialization code
        super.init(frame: frame)
    }

    /*
    override func drawRect(rect: CGRect)
    {
        // Drawing code
    }
    */
}

我将此RectangleView添加到我的CustomViewController上:
import UIKit

class CustomViewController: UIViewController
{
    var ballX:Int = 0
    var ballY:Int = 0
    let BALLWIDTH:Int = 50
    let BALLHEIGHT:Int = 50
    var navigationHeight:Double = 0.0
    var pos:CGPoint?
    var rectangleView:RectangleView?

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

        self.ballX = Int(arc4random_uniform(320));
        self.ballY = Int(arc4random_uniform(480));
        self.navigationHeight = Double(self.navigationController.navigationBar.frame.size.height)
        var rect = CGRect(x: 0, y: 0, width: self.BALLWIDTH, height: self.BALLHEIGHT)
        self.pos = CGPoint(x: self.ballX, y: self.ballY);

        println("x: \(self.ballX), y: \(self.ballY)")

        self.rectangleView = RectangleView(frame: rect)
        self.rectangleView!.backgroundColor = UIColor.redColor()

        self.view.addSubview(self.rectangleView!)

        NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("moveBall"), userInfo: nil, repeats: true)
    }

    func moveBall()
    {
        self.rectangleView!.center = CGPointMake(self.rectangleView!.center + self.pos!.x, self.rectangleView!.center + self.pos!.y)
    }
...

我收到一条错误消息
'RectangleView?' does not have a member named 'center'

我应该在center上定义此RectangleView吗?我的RectangleView继承自UIView,所以我感到非常困惑。感谢您的帮助。

编辑

我用这个代码
func moveBall()
{
    if let rv = self.rectangleView {
        rv.center = CGPointMake(rv.center + self.pos!.x, rv.center + self.pos!.y)
    }

我收到新的错误消息
'CGPoint' is not convertible to 'UInt8'

我认为rv.center类型是UInt8,但是self.post!.xnsnumber,那么我如何转换为CGPointMake接受类型?我已经转换了UInt8(self.pos!.x)并将计算结果再次转换为CGPointMake接受类型?

还有其他最佳方法吗?感谢您的帮助。

最佳答案

! -unwrapping可选参数返回的值当前是不可变的(请参见Lattner's explanation)。

尝试:

if let rv = self.rectangleView {
  rv.center = ...
}

我认为这可以视为Swift中的已知错误。

08-26 22:25