В настоящее время в моем приложении, когда пользователь нажимает на экран, красная точка появляется везде, где пользователь касается, если пользователь нажимает на экран несколько раз, будет несколько точек. Я хочу добавить функцию, позволяющую пользователю изменять цвет.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first as UITouch?{
let location = (touch as! UITouch).location(in: self.imageView)
let layer = CAShapeLayer()
layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
layer.fillColor = UIColor.red.cgColor
imageView.layer.addSublayer(layer)
}
}
Когда я попробовал следующий метод, я смог изменить цвет, но по какой-то причине, независимо от того, сколько раз я нажимал на экран, будет только одна точка. Я предполагаю, что каждый раз, когда я нажимаю на свой экран, будет создан новый слой, который заменит старый слой. Могу ли я разрешить пользователю изменять цвет слоя, сохраняя при этом все точки, которые уже есть на слое?
class ViewController: UIViewController,UIScrollViewDelegate {
let layer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first as UITouch?{
let location = (touch as! UITouch).location(in: self.imageView)
layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
layer.fillColor = UIColor.red.cgColor
imageView.layer.addSublayer(layer)
}
}
@IBAction func changecolorBtn(_ sender: Any) {
layer.fillColor = UIColor.green.cgColor
}
}
Из-за того, что вы использовали только один слой
let layer = CAShapeLayer()
и всякий раз, когда вы устанавливаете
layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
Он удалит старый путь, и ваш новый путь будет иметь только одну точку.
Вот почему
When I tried the following method I am able to change the colour but for some reason no matter how many times I've tap on the screen there will only be one dot.
Вы можете просто исправить проблему, объединив все свои dot path
. Нравится
// add the combine path as your global variable
let layer = CAShapeLayer()
let combinePath = CGMutablePath()
и измените свой код добавления пути
layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
добавить путь комбинирования
let path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
combinePath.addPath(path)
layer.path = combinePath