我想将变量引用到特定函数。但是,有一个错误叫做Value of type 'UIView' has no member 'lineTo'
Clearly, the whatSelectObject
variable contains the classes that which members are exists. 所以我使用了 If 语句,“可选绑定”。但结果是一样的。
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class ObjectView: UIView {
var outGoingLine : CAShapeLayer?
var inComingLine : CAShapeLayer?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func lineTo(connectToObj: ObjectView) -> CAShapeLayer {
let path = UIBezierPath()
path.move(to: CGPoint(x: self.frame.maxX, y: self.frame.midY))
path.addLine(to: CGPoint(x: connectToObj.frame.minX, y: connectToObj.frame.midY))
let line = CAShapeLayer()
line.path = path.cgPath
line.lineWidth = 5
line.fillColor = UIColor.clear.cgColor
line.strokeColor = UIColor.gray.cgColor
connectToObj.inComingLine = line
outGoingLine = line
return line
}
}
class MyViewController : UIViewController {
var whatSelectView: UIView?
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let object = ObjectView(frame: CGRect(x: 10, y: 100, width: 100, height: 100))
object.backgroundColor = UIColor.orange
view.addSubview(object)
whatSelectView = object
let object2 = ObjectView(frame: CGRect(x: 200, y: 200, width: 100, height: 100))
object2.backgroundColor = UIColor.red
view.addSubview(object2)
if let s = whatSelectView {
view.layer.addSublayer(s.lineTo(connectToObj: object2)) // error
}
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
!此代码是相关简化代码的示例,以帮助受访者理解它。我可以直接引用object
变量,但我必须绝对引用whatSelectView
。
为什么会导致引用变量出错?还是我对可选绑定有误?