【发布时间】:2017-02-21 08:36:22
【问题描述】:
我想要达到的目标:
尝试在屏幕上抓取当前触摸区域的坐标,并将接收到的坐标绘制在屏幕上。简而言之,一个基本的绘图应用程序,全部以编程方式编写(用于我自己的实践)。
问题
touchesBegan 和 touchesMoved for PaintingSubclass 根本没有被调用。
当前设置
我有一个
PaintingViewController,然后我也有一个PaintingSubclass。PaintingViewController是UIViewController,PaintingSubclass是UIView。PaintingViewController创建PaintingSubclass的实例并将其添加到PaintingViewController的子视图。-
PaintingSubclass是实际绘图发生的地方。
到目前为止我已经尝试过什么
- 在
touchesMoved中放置一个断点并touchesBegan (没有用) - 尝试添加
UITapGestureRecognizer(无效) - 启用
self.isUserInteractionEnabled = true(无效) - 使
PaintingSubclass继承UIControl并在touchesMoved和touchesBegan的末尾调用sendActions(for: .valueChanged)(不起作用)
当前代码
(请忽略任何不必要的变量)
import UIKit
class PaintingViewController: UIViewController{
var _paintView: PaintingSubclass? = nil
override func loadView() {
view = UILabel()
}
private var labelView: UILabel {
return view as! UILabel
}
override func viewDidLoad() {
_paintView = PaintingSubclass()
_paintView?.frame = CGRect(x: view.bounds.minX, y: view.bounds.minY, width: 400, height: 750)
_paintView?.backgroundColor = UIColor.white
_paintView?.setNeedsDisplay()
view.addSubview(_paintView!)
}
class PaintingSubclass: UIView{
private var context: CGContext? = nil
var styleSelection: String = "buttcap"
var linewidth: Float = 5
var lineCapStyle: CGLineCap? = nil
var lineJoinStyle: CGLineJoin? = nil
var lineWidthValue: CGFloat? = nil
var colorValue: UIColor? = nil
override init(frame: CGRect) {
super.init(frame: frame)
lineWidthValue = 0.5
colorValue = UIColor(cgColor: UIColor.black.cgColor)
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
context = UIGraphicsGetCurrentContext()!
context?.move(to: CGPoint(x: 0.0, y: 110.0))
context?.setStrokeColor((colorValue?.cgColor)!)
context?.drawPath(using: CGPathDrawingMode.stroke)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let touch: UITouch = touches.first!
let touchPoint: CGPoint = touch.location(in: self)
let _xValue = touchPoint.x
let _yValue = touchPoint.y
NSLog("coordinate: \(_xValue), \(_yValue)")
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
let touch: UITouch = touches.first!
let touchPoint: CGPoint = touch.location(in: self)
let _xValue = touchPoint.x
let _yValue = touchPoint.y
NSLog("coordinate: \(_xValue), \(_yValue)")
}
}
}
我在这里做错了什么?被困在这种状态好几个小时没有取得任何进展。任何帮助/反馈将不胜感激。
【问题讨论】:
-
你试过检查它的权限吗?根据我的经验,这通常会触发一些事情
-
view = UILabel()这行说明了什么? -
你能添加你的 UI 图像吗?
-
能否将autoresizingMask的flexibleWidth和flexibleHeight设置为子类view..然后添加super.init(coder:aDecoder)
-
问题是一个非常简单的问题...我只需要在 VIEW 而不是 self 上启用 isUserInteractionEnabled 为 true。哇!
标签: ios swift uiview uiviewcontroller touchesbegan