开发者

How to set up a button to invert two textFields

开发者 https://www.devze.com 2023-04-07 11:26 出处:网络
I\'m an absolute beginner, and I need to have a button to in开发者_开发百科vert two text fields:

I'm an absolute beginner, and I need to have a button to in开发者_开发百科vert two text fields:

text1 <—> text2

- (IBAction)swapText {
    name.text = surname.text;
    surname.text = name.text;
}

I know that I have to retain the values and then release them, but I'm not sure how to write it.


This is quite simple: the only text / NSString you have to retain is the one that will stop being hold by the UITextField itself, namely the name.text that you will replace by surname.text.

- (IBAction)swapText {
  NSString* temp = [name.text retain];
  name.text = surname.text;
  surname.text = temp;
  [temp release];
}


The only objects you need to take care of would be alloc/deallocating the UITextFields. Assuming your UITextfields are ivars (declared in your header file) you can use the following code:

- (void)viewDidLoad 
{
  [super viewDidLoad];
  CGRect b = [[self view] bounds];

  _txt1 = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMidX(b)-100, 50, 200, 29)];
  [_txt1 setBorderStyle:UITextBorderStyleRoundedRect];
  [[self view] addSubview:_txt1];

  _txt2 = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMidX(b)-100, 100, 200, 29)];
  [_txt2 setBorderStyle:UITextBorderStyleRoundedRect];
  [[self view] addSubview:_txt2];

  UIButton* btnSwap = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [btnSwap setFrame:CGRectMake(CGRectGetMidX(b)-75, 150, 150, 44)];
  [btnSwap setTitle:@"Swap Text" forState:UIControlStateNormal];
  [btnSwap addTarget:self action:@selector(tappedSwapButton) forControlEvents:UIControlEventTouchUpInside];
  [[self view] addSubview:btnSwap];
}

- (void)tappedSwapButton
{
  NSString* text1 = [_txt1 text];
  NSString* text2 = [_txt2 text];

  [_txt2 setText:text1];
  [_txt1 setText:text2];
}

- (void)dealloc
{
  [_txt1 release];
  [_txt2 release];

  [super dealloc];
}


Based on your code given, your text in the first textfield will be lost. The easiest way to fix that is to declare a temp NSString object that will hold the string that is contained in name.text:

- (IBAction)swapText{

  // create a temp string to hold the contents of name.text
  NSString *tempString = [NSString stringWithString: name.text];

  name.text = surname.text;
  surname.text = tempString;
}

Since you are using dot notation, it is assumed that "name" and "surname" are properties for the IBOutlet references to both textfields that you want to swap. If this is the case, as long as you have "retain" for both of these properties, that will take care of the memory management (as long as you release these in the dealloc method in the .m file).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号