我的代码使用 didTapAdd 函数向视图控制器添加无穷无尽的文本视图。问题是我不能移动它,因为它是一个文本视图。如果它是标签或图像视图,这将完美地工作。不知何故,我想做一个类似于开关 everttime didtapadd2 的事情,我希望所有的文本视图都不能输入,所以我可以移动它们,然后再次调用 func 以将其关闭。
import UIKit
class ViewController: UIViewController {
var addButton = UIButton()
var cutOff = UIButton()
var count: Int = 0
var ht = -90
var arrTextFields = [UITextView]()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(addButton);view.addSubview(cutOff)
cutOff.backgroundColor = .systemPink
addButton.backgroundColor = .systemOrange
addButton.frame = CGRect(x: view.bounds.midX - 80, y: view.bounds.midY, width: 50, height: 50)
cutOff.frame = CGRect(x: view.bounds.midX - 80, y: view.bounds.midY+60, width: 50, height: 50)
addButton.addTarget(self, action: #selector(didTapAdd), for: .touchUpInside)
cutOff.addTarget(self, action: #selector(didTapAdd2), for: .touchUpInside)
}
@objc func didTapAdd() {
let subview = UITextView()
subview.isUserInteractionEnabled = true
subview.isMultipleTouchEnabled = true
arrTextFields.append(subview)
view.addSubview(subview)
subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: 50, height: 30)
subview.backgroundColor = .systemTeal
subview.tag = count
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
subview.addGestureRecognizer(pan)
count += 1
ht += 50
arrTextFields.append(subview)
}
@objc func didTapAdd2() {
cutOff.isSelected = !cutOff.isSelected
arrTextFields.forEach { $0.isScrollEnabled = cutOff.isSelected }
}
@objc func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
let draggedView = gesture.view!
view.bringSubviewToFront(draggedView)
let translation = gesture.translation(in: view)
draggedView.center = CGPoint(x: draggedView.center.x + translation.x, y: draggedView.center.y + translation.y)
gesture.setTranslation(.zero, in: view)
}
}