【问题标题】:swift uiview does not have a member named center and not convertible to UIViewswift uiview 没有名为 center 的成员,不能转换为 UIView
【发布时间】:2015-03-20 12:27:21
【问题描述】:

我创建了一个模型类“鱼”的数组,并希望在我的视图加载时显示在视图上。我收到错误消息:

'Fish' 没有名为 'center' 的成员 '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)
    }   
}

【问题讨论】:

  • 为什么你认为鱼是一种风景?为什么不只拥有一组图像视图?
  • typo:fish.center.x = CGPoint(x: x, y: y) --> fish.center = CGPoint(x: x, y: y)。我仍然有同样的错误。
  • 请更正问题而不是添加 cmets
  • Fish 是一个 UIImageView。但是为什么斯威夫特告诉我鱼不是一种观点。我需要将鱼添加到我的视图中。
  • 因为 fish 不是你的代码现在的图像视图。您必须使其成为 UIImageView 的子类才能成为 UIImageView

标签: iphone swift uiview uiimageview uiimage


【解决方案1】:

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)

【讨论】:

  • 有了这个答案,您实际上可以只设置fish.center,而不必总是引用imageView fish.imageView.center,并且您将整条鱼作为对象添加到您的视图中,而不仅仅是它图像视图
【解决方案2】:
fish.imageView.center = CGPoint(x: x, y: y)
view.addSubview(fish.imageView)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多