swift uiview没有名为center的成员且不能转换为UIView

时间:2015-01-21 20:45:01

标签: iphone swift uiview uiimageview uiimage

我创建了一个de model类'fish'的数组,并希望在我的视图加载时在视图上显示。我收到了错误消息:

'鱼'没有名为'中心'的成员 '鱼'不能转换为'UIView'

请参阅下面的代码。我会感激任何帮助。感谢

这是我的自定义类:

class Fish {
var imageView = UIImageView(image: UIImage(named: "fish_3"))
}

这是我的视图控制器:

class ViewController: UIViewController {

var fishes:[Fish] 

required init(coder aDecoder: NSCoder) {
    fishes = [Fish]() 

    var fish3 = Fish()
    fish3.imageView = UIImageView(image: UIImage(named: "fish_3"))
    fishes.append(fish3)

    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()

    for fish in fishes {
    var x = CGFloat(arc4random_uniform(120))
    var y = CGFloat(arc4random_uniform(200))
    fish.center.x = CGPoint(x: x, y: y)
    view.addSubview(fish)
    }   
}

2 个答案:

答案 0 :(得分:1)

fish.imageView.center = CGPoint(x: x, y: y)
view.addSubview(fish.imageView)

答案 1 :(得分:0)

Fish应该以某种方式从UIView继承,最好的方法是使它成为UIImageView的子类

class Fish: UIImageView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        // Setup
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // Setup
    }
}

现在初始化时:

var fish3 = Fish(frame: CGRectMake(0, 0, 50, 50))
fish3.image = UIImage(named: "fish_3")
fishes.append(fish3)