我对 iOS 开发非常陌生,但我正在努力解决视图的位置问题。
在单个视图控制器上,我试图通过长按视图在视图上画一个圆圈,但我只能在视图的中心制作它。你知道如何在我选择的地方画一个圆圈吗?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
longPressView()
}
let addCircle = UIButton()
let circleAddDefaultSize: Int = 10
func longPressView() {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressForView))
view.addGestureRecognizer(longPress)
}
override var canBecomeFirstResponder: Bool {
return true
}
//Long press then MenuItem comes up
@objc func longPressForView(sender: UILongPressGestureRecognizer) {
if sender.state == .began {
let menu = UIMenuController.shared
becomeFirstResponder()
let menuItemAdd = UIMenuItem(title: "Add", action: #selector(addCircleMenuItemAction))
let menuItemDelete = UIMenuItem(title: "Delete", action: #selector(handleMenuItemAction))
menu.menuItems = [menuItemAdd, menuItemDelete]
//I want to use this location in addCircleMenuItemAction()
let location = sender.location(in: sender.view)
let menuLocation = CGRect(x: location.x, y: location.y, width: 0, height: 0)
menu.showMenu(from: sender.view!, rect: menuLocation)
}
}
//Press add button and I want to add a button on that location
@objc func addCircleMenuItemAction() {
print("Add item tapped")
view.addSubview(addCircle)
addCircle.layer.cornerRadius = CGFloat(circleAddDefaultSize/2)
addCircle.translatesAutoresizingMaskIntoConstraints = false
addCircle.backgroundColor = .black
//Create constraints
//Instead of using this center constraints, how can I use the location from longPressForView() ?
let centerX = NSLayoutConstraint(item: addCircle, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)
let centerY = NSLayoutConstraint(item: addCircle, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)
addCircle.widthAnchor.constraint(equalToConstant: CGFloat(circleAddDefaultSize)).isActive = true
addCircle.heightAnchor.constraint(equalToConstant: CGFloat(circleAddDefaultSize)).isActive = true
addCircle.isUserInteractionEnabled = true
view.addConstraints([centerX, centerY])
}
当我运行它时,我只能将圆形按钮放在视图的中心。