Move a label left from its position in swift

6.2k Views Asked by At

I have put a label in a text box and I want to shift this label to left side after tapping this text box. In the following screenshot 'hello' is a label and I want to shift it left after tapping on the text box.

enter image description here

I wrote the following code but the 'textFieldDidBeginEditing' function is not called

@IBOutlet weak var lblhello: UILabel!
func textFieldDidBeginEditing(numtxt: UITextField!) {    //delegate method
    lblhello.frame = CGRectMake(98, 156, 42, 21)
}
1

There are 1 best solutions below

0
On BEST ANSWER

I'm making the assumption based on previous comments that you want to manually specify the frame size, and aren't using constraints.

First off, you need to add UITextFieldDelegate to your viewController.

This is done like so in the beginning of your VC class:

class yourViewControllerName: UIViewController, UITextFieldDelegate {

Then you want to specify the delegate of your UITextField, (most likely in viewDidLoad)

yourTextFieldName.delegate = self

Now you can use the textFieldDelegate functions. The on you're looking for is probably this:

func textFieldDidBeginEditing(textField: UITextField) -> Bool {
    lblhello.frame = CGRectMake(160, 200, 60, 40)
    return true
}

If everything is set up correctly that should change the frame of lblhello when a user begins editing your UITextField.

One common problem I often hear for people saying this doesn't work. Is caused by the label being specified in viewDidLoad(). Most of the time you want to declare the label before viewDidLoad(), otherwise functions like this doesn't have access to it.

In case you want to move it back to it's original position afterwards. You do almost the same as you did in textFieldDidBeginEditing except you use textFieldDidEndEditing instead.

However, on a side-note. I do suggest getting used to using constraints rather than setting the frame for things like this.