导航栏用来显示应用的标题。在xib文件中拖动一个Navigation Bar,用来显示应用标题。title改为:小小词典。颜色改为亮黄色。再添加一个Bar Button item用来表示是汉译英还是英译汉。将Bar Button item放到Navigation Bar的左上角。
将4个png图片拖入工程。英中.png(20x20) 英中@2x.png(40x40) 中英.png(20x20) 中英@2x.png(40x40)
再将查询按钮图片,查询.png,查询@2x.png拖入工程。
Bar button item设置图片英中.png,按钮设置图片查询.png。
为bar button item selector 关联方法- (IBAction)pressExchange:(UIBarButtonItem *)sender;
定义BOOL 变量,表示从英文到中文还是从中文到英文。
修改源文件。
// // ViewController.m // TinyDictionary // // Created by cloud on 13-3-26. // Copyright (c) 2013年 cloud. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)dealloc { [_textField release]; [_lblResult release]; [super dealloc]; } - (IBAction)pressExchange:(UIBarButtonItem *)sender { _chineseToEnglish=!_chineseToEnglish; if (_chineseToEnglish) { sender.image=[UIImage imageNamed:@"中英"]; } else { sender.image=[UIImage imageNamed:@"英中"]; } } - (IBAction)pressFind:(UIButton *)sender { if ([_textField.text length]==0) { return; } //GB2312字符集 NSStringEncoding encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSString *strURL=nil; if (_chineseToEnglish) { //编码中文url strURL=[[NSString stringWithFormat:@"http://api.liqwei.com/translate/?language=zh-CN|en&content=%@",_textField.text] stringByAddingPercentEscapesUsingEncoding:encode]; } else { //编码中文url strURL=[[NSString stringWithFormat:@"http://api.liqwei.com/translate/?language=en|zh-CN&content=%@",_textField.text] stringByAddingPercentEscapesUsingEncoding:encode]; } NSURL* url=[NSURL URLWithString:strURL]; NSError *err=nil; //以指定编码得到url给出的内容 NSString *strResult=[NSString stringWithContentsOfURL:url encoding:encode error:err]; if (err) { NSLog(@"error=%@",[err description]); } else { _lblResult.text=strResult; } } @end
源码地址:http://download.csdn.net/detail/cloud95/5183617