添加到UIView时,UITextField不响应触摸事件

时间:2016-07-02 10:19:40

标签: ios iphone swift uiview uitextfield

我遇到UITextField的问题,当它被添加到ContainerView时,它不会响应触摸事件。当我尝试将UITextField添加到主UIViewController时,它看起来很好并且响应(键盘显示)。

我试图将子视图带到前面,在ContainerView上启用用户交互 - 没有任何帮助。

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.scrollView = UIScrollView()
    self.containerView = UIView()

    self.scrollView.delegate = self
    self.containerView.userInteractionEnabled = true

    self.scrollView.addSubview(containerView)
    self.view.addSubview(scrollView)

    registerForKeyboardNotifications()
    setupGesturesAndMap()
    setupActivityIndicator()
    setupCircleButton()
    setupBrowseTextField()

    // Initializing status
    status = Status.Init
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    scrollView.frame = self.view.bounds
    containerView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)
}

并且有负责设置browseTextField的函数:

func setupBrowseTextField() {

    // Setup of browseTextField
    browseTextField = UITextField(frame: CGRectMake(10, self.view.frame.height / 2, self.view.frame.width - 20, self.view.frame.height / 12))
    browseTextField.placeholder = "Enter your destination here"
    browseTextField.font = UIFont.systemFontOfSize(15)
    browseTextField.borderStyle = UITextBorderStyle.RoundedRect
    browseTextField.autocorrectionType = UITextAutocorrectionType.No
    browseTextField.keyboardType = UIKeyboardType.Default
    browseTextField.returnKeyType = UIReturnKeyType.Done
    browseTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
    browseTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
    browseTextField.delegate = self

    containerView.addSubview(browseTextField)
}

你们中有人有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我发现你已经将containerView的框架设置为

containerView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)

scrollView.contentSize.width为0。

这解决了您的问题。

containerView.frame = self.view.bounds

此外,您可以通过scrollView的帧大小为

提供containerView大小
containerView.frame = CGRectMake(0, 0, scrollView.frame.width, scrollView.frame.height)