我正在尝试制作一个练习应用程序,它接受两个输入的单词(word1,word2)并将它们组合在一起形成一个复合词。我对此非常陌生,想知道在“buttonPressed”操作下显示这两个变量的正确方法。
这是头文件......
#import <UIKit/UIKit.h>
@interface Word_CombinerViewController : UIViewController {
UITextField *word1;
UITextField *word2;
UITextField *display;
UIButton *mashButton;
}
@property (nonatomic, retain) IBOutlet UITextField *word1;
@property (nonatomic, retain) IBOutlet UITextField *word2;
@property (nonatomic, retain) IBOutlet UITextField *display;
@property (nonatomic, retain) IBOutlet UIButton *mashButton;
-(IBAction)textFieldDoneEditing:(id)sender;
-(IBAction)backgroundTap:(id)sender;
-(IBAction)buttonPressed:(id)sender;
@end
这是实施文件(.m)......
#import "Word_CombinerViewController.h"
@implementation Word_CombinerViewController
@synthesize word1;
@synthesize word2;
@synthesize display;
@synthesize mashButton;
-(IBAction)textFieldDoneEditing:(id)sender {
[sender resignFirstResponder];
}
-(IBAction)backgroundTap:(id)sender {
[word1 resignFirstResponder];
[word2 resignFirstResponder];
}
-(IBAction)buttonPressed:(id)sender {
NSString *newText = [NSString: @word1, @word2]
display.text = newText;
[newText release]
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[word1 release];
[word2 release];
[display release];
[mashButton release];
[super dealloc];
}
@end
我知道这段代码可能充满了错误,但是每个人都必须从某个地方开始,对吧? 非常感谢任何反馈,谢谢!
答案 0 :(得分:2)
NSString *newText = [NSString: @word1, @word2]
这段代码没有任何意义。消息的第一部分是接收者,它不会有任何冒号。第二部分是消息本身,即方法名称以及任何必要的参数。你在寻找的是:
NSString *newText = [NSString stringWithFormat:@"%@%@", word1, word2];
-stringWithFormat:方法使用格式字符串(非常类似于printf())和可变数量的参数来填充格式字符串中的占位符。
此外,当您使用这样的“便捷方法”创建字符串(或任何对象)时,不应释放它。您没有保留或分配或复制它,因此发布它不是您的责任。您将要从-buttonPressed方法中删除该行。
答案 1 :(得分:0)
试试这个:
-(IBAction)buttonPressed:(id)sender {
NSString *newText = [word1.text stringByAppendingString:word2.text]
display.text = newText;
}
答案 2 :(得分:0)
这是你出错的地方。
-(IBAction)buttonPressed:(id)sender {
NSString *newText = [NSString stringWithFormat:@"%@ %@", word1.text word2.text]
display.text = newText;
[newText release]
}