我目前正在编写一个思维导图应用程序,应用程序用户可以在空白页面上的任意位置添加文本字段。有没有办法做类似的事情。我想出的一种不专业的方法是向 ViewController 添加几百个空文本字段,然后用户可以填写这些文本字段。但是我确信有更好的方法。如果用户可以点击“添加文本”按钮来生成一个可以在空白页面上移动的文本字段(就像在 Microsoft Word 中一样),那就太好了。我真的想不出有什么类(class)可以解决这样的任务。有人可以帮忙吗?
干杯
最佳答案
您始终可以通过编程方式创建文本字段。在 ViewController 文件中,您需要创建 UITextField
的实例。有关 UITextField 的信息,请查看 this documentation .
例如,在 iOS 上,当用户用一根或多根手指触摸屏幕时,将调用 View Controller 上的方法。当用户触摸屏幕时,iOS 会调用 View Controller 上的 touchesBegan
和 touchesEnded
。在您的情况下,您可能需要 touchesEnded
,以便在用户抬起手指之前不会添加该字段。这些方法传递一组UITouch
。 UITouch Class Reference
Swift 中的 View Controller 代码示例:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("Touch Ended")
for touch in touches {
let touchPoint = touch.locationInView(self.view)
let fieldFrame = CGRect(x: touchPoint.x, y: touchPoint.y, width: 100, height: 30)
let textField = UITextField(frame: fieldFrame)
textField.placeholder = "Type Here"
view.addSubview(textField)
}
}
}
您可能已经知道如何以编程方式布局 View ,但是......
此代码查找触摸位置并将该位置作为文本字段的原点。在这里,我只是在将文本字段添加到 View 之前设置其框架,将宽度硬编码为 100,高度为 30。在实践中,您可能需要研究类似 AutoLayout 的内容,特别是 NSLayoutConstraint ,它允许考虑边界变化的编程约束。 如果他们同时用多个手指触摸屏幕,您可能也不想为每次触摸添加文本字段。
这允许将字段放置在用户触摸的任何位置。或者,您可以创建一个按钮来添加您所说的文本字段,然后只需为要添加的 UITextField
提供一个默认位置,而不是观察触摸。
拖动文本字段
要在用户拖动文本字段时移动字段,您需要观察触摸,并在触摸时检查文本字段,这本质上是 checking for a subview at a point .
然后,您可以使用 touchesMoved
来观察拖动并通过 AutoLayout 或您决定使用的任何程序更新文本字段的位置。
手势识别器
作为 touchesBegan
、touchesMoved
、touchesEnded
的替代方案,您可以使用手势识别器。从 Apple's documentation 查看有关不同类型 UITapGestureRecognizer
的信息。这些可以通过指定目标和操作方法来创建,然后添加到 View 中。
创建点击手势识别器并将其添加到存储在名为 textfield 的变量中的 UITextField 的示例。
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("textFieldTapped:"))
textfield.addGestureRecognizer(tapRecognizer)
关于xcode - 为 MindMapping 应用程序 Swift/xcode 在应用程序内生成文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34485020/