这是我的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!.x
为nsnumber
,所以我怎么能转换为CGPointMake
接受类型?我已转换UInt8(self.pos!.x)
并将计算结果再次转换为CGPointMake
接受类型?
还有其他最好的方法吗?谢谢你的帮助。
答案 0 :(得分:7)
!
返回的值 - 展开可选项目前是不可变的(请参阅Lattner's explanation)。
尝试:
if let rv = self.rectangleView {
rv.center = ...
}
我认为这可以被认为是Swift中的已知错误。