iOS 5 编程(2)-开关(UISwitch)、分段控件(UISegmentedControl)和Web视图(UIWebView)控件的使用
本范例iOS App演示了如下控件的使用,从第三方网站获取特定URL的Web内容,并显示在UIWebView控件中。
- 开关(UISwitch)
- 分段控件(UISegmentedControl)
- Web视图(UIWebView)
该范例 iPhone App运行效果如下所示:
下面是iOS App获取特定URL Web内容的主要代码:
- (IBAction)getFlower:(id)sender {
NSURL *imageURL;
NSURL *detailURL;
NSString *imageURLString;
NSString *detailURLString;
NSString *color;
int sessionID;
color =[self.colorChoice titleForSegmentAtIndex:self.colorChoice.selectedSegmentIndex];
sessionID = random() % 50000;
imageURLString = [[NSString alloc] initWithFormat:
@"http://www.floraphotographs.com/showrandomios.php?color=%@&session=%d", [dicColor objectForKey:color], sessionID];
detailURLString = [[NSString alloc] initWithFormat:
@"http://www.floraphotographs.com/detailios.php?session=%d", sessionID];
imageURL = [[NSURL alloc] initWithString:imageURLString];
detailURL = [[NSURL alloc] initWithString:detailURLString];
[self.flowerView loadRequest:[NSURLRequest requestWithURL:imageURL]];
[self.flowerDetailView loadRequest:[NSURLRequest requestWithURL:detailURL]];
self.flowerDetailView.backgroundColor = [UIColor clearColor];
}
NSURL *imageURL;
NSURL *detailURL;
NSString *imageURLString;
NSString *detailURLString;
NSString *color;
int sessionID;
color =[self.colorChoice titleForSegmentAtIndex:self.colorChoice.selectedSegmentIndex];
sessionID = random() % 50000;
imageURLString = [[NSString alloc] initWithFormat:
@"http://www.floraphotographs.com/showrandomios.php?color=%@&session=%d", [dicColor objectForKey:color], sessionID];
detailURLString = [[NSString alloc] initWithFormat:
@"http://www.floraphotographs.com/detailios.php?session=%d", sessionID];
imageURL = [[NSURL alloc] initWithString:imageURLString];
detailURL = [[NSURL alloc] initWithString:detailURLString];
[self.flowerView loadRequest:[NSURLRequest requestWithURL:imageURL]];
[self.flowerDetailView loadRequest:[NSURLRequest requestWithURL:detailURL]];
self.flowerDetailView.backgroundColor = [UIColor clearColor];
}
上述代码简要解释一下,其基本过程是:
- 首先创建一个NSString 字符串,也就是web网址;
- 根据web网址,创建一个NSURL实例,调用initWithString方法;
- 再创建一个可将其传递给Web视图进行加载的NSURLRequest对象,调用requestWithURL方法;
- 最后,将该请求传递给Web 视图的loadRequest 方法,该方法将接管工作,并处理加载过程,在Web 视图中呈现网页内容。