Search code examples
uitextfieldswift2viewwithtag

Retrieve text from UITextField using viewWithTag function


I'm trying to retrieve text from a UITextField that I allow the user to create at runtime. I'm using the following line of code.

let thisTextField:UITextField = self.scrollView.viewWithTag(0) as! UITextField

The compiler error states

Could not cast value of type 'UIScrollView' (0x1032faaf0) to 'UITextField' (0x103318dc0).

I've looked through stackoverflow and the above code appears to have worked with previous versions of Swift but does not appear to work with Swift 2.0.


Solution

  • I have had similar issues with this. Since view tags are non optional it would seem that they are initially set as 0. This means that when it looks for a view with the tag 0 it finds the scrollview and returns that. A couple of solutions would be to set the textField to a value other than 0 or make your textField a class variable.