上繪製x vs y圖時遇到了麻煩我是iOS開發的初學者。除了實際繪製x vs y圖之外,我已在iTunes U(手勢,視圖控制器,視圖,賽格等)上完成2016年斯坦福大學CS193P iOS開發課程的作業3(繪圖計算器)的所有工作。我對於在哪裏以及如何讓我的代碼執行此操作感到困惑;以及drawRect將從中獲取y值的位置。我已經在互聯網上搜索了一個適合年齡的解決方案我假設圖形視圖控制器的模型是CalculatorBrain或可能是大腦程序,但我不太確定視圖如何從drawRect函數與此控制器交談以獲取y值一個點x。如果你能把我放在正確的軌道上,這將是非常有益的。我將在下面粘貼我的圖形視圖控制器和圖形視圖代碼。提前致謝。在斯坦福CS193P任務3(2016)
//GraphViewController
import UIKit
class GraphViewController: UIViewController {
private var brain = CalculatorBrain()
var program: [AnyObject]?
@IBOutlet weak var graphView: GraphingView! {
didSet {
graphView.addGestureRecognizer(UIPinchGestureRecognizer(target: graphView, action: #selector (GraphingView.changeScale(_:))))
graphView.addGestureRecognizer(UIPanGestureRecognizer(target: graphView, action: #selector(GraphingView.panView(_:))))
graphView.addGestureRecognizer(UITapGestureRecognizer(target: graphView, action: #selector(GraphingView.doubleTapOrigin(_:))))
}
}
}
//GraphingView
import UIKit
@IBDesignable
class GraphingView: UIView {
@IBInspectable var scale: CGFloat = 50 { didSet { setNeedsDisplay() } }
@IBInspectable var linewidth: CGFloat = 2 { didSet { setNeedsDisplay() } }
var origin: CGPoint! { didSet { setNeedsDisplay() } }
/* Gesture Code
func changeScale (recognizer: UIPinchGestureRecognizer) {
switch recognizer.state {
case .Changed,.Ended:
scale *= recognizer.scale
recognizer.scale = 1.0
default:
break
}
}
func panView (recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .Changed,.Ended:
origin.x += recognizer.translationInView(self).x
origin.y += recognizer.translationInView(self).y
recognizer.setTranslation(CGPoint(x:0,y:0), inView: self)
default:
break
}
}
func doubleTapOrigin (recognizer: UITapGestureRecognizer) {
recognizer.numberOfTapsRequired = 2
switch recognizer.state {
case .Ended :
origin = CGPoint(x: recognizer.locationInView(self).x, y:recognizer.locationInView(self).y)
default: break
}
}
*/
var axesDrawer = AxesDrawer()
override func drawRect(rect: CGRect) {
if origin == nil {
origin = CGPoint(x: bounds.midX, y: bounds.midY)
}
axesDrawer.drawAxesInRect(rect, origin: origin, pointsPerUnit: scale)
var pixelX = 0
while pixelX <= bounds.maxX {
//do some code to get value of y for current x from the brain in the view controller and plot it with UIBezierPath
pixelX += 1/contentScaleFactor
}
}
}
非常感謝您的幫助。這是唯一的方法嗎?它沒有在任務中說出任何關於協議的內容(並且根據我所理解的講師在講授關於協議之前發佈的任務)。我認爲這就是讓我困惑的原因。 –
我用另一種方式更新了答案,以更好地符合教授的意圖。 – vacawama
非常感謝! –