我希望你很好,我已经在iphone上工作了几个星期,目前我有一个问题尝试用网址打开一个野生动物园,我有一个json文件来一个网址,这是一个dinamic。< / p>
这里我留下了代码。
- (void) loadFiles {
NSArray *_json = [[[self getDataFromJson] objectAtIndex:0] retain];
if ([_json count] > 0)
{
for (int i = 0; i < [_json count]; i++)
{
NSDictionary *file = [_json objectAtIndex:i];
UIImage *buttonImage = [UIImage imageNamed:@"btn.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button addTarget:self action:@selector(openBrowser:) forControlEvents:UIControlEventTouchUpInside];
//works but i have warnings
button.tag = [file objectForKey:@"linkURL"] ;
CGRect frame = CGRectZero;
frame.size = buttonImage.size;
button.frame = frame;
NSString *name = [file objectForKey:@"name"];
NSString *description = [file objectForKey:@"description"];
//Create Box
}
}
}
- (void) openBrowser:(id)sender
{
NSString *url = ((UIControl *) sender).tag;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] ];
}
我需要从UIButtom打开一个没有投诉的网址。 任何建议或帮助,谢谢你。 干杯
答案 0 :(得分:4)
子类UIButton
并添加一个属性来存储URL。
// MyButton.h
@interface MyButton : UIButton {
NSString *urlString_;
}
@property (nonatomic, retain) NSString *urlString;
@end
// MyButton.m
#import "MyButton.h"
@implementation MyButton
@synthesize urlString = urlString_;
- (void)dealloc {
[self setUrlString:nil];
[super dealloc];
}
@end
然后继续使用您的代码:
#import "MyButton.h"
.
.
.
- (void) loadFiles {
NSArray *_json = [[[self getDataFromJson] objectAtIndex:0] retain];
if ([_json count] > 0)
{
for (int i = 0; i < [_json count]; i++)
{
NSDictionary *file = [_json objectAtIndex:i];
UIImage *buttonImage = [UIImage imageNamed:@"btn.png"];
MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button addTarget:self action:@selector(openBrowser:) forControlEvents:UIControlEventTouchUpInside];
//works but i have warnings
button.urlString = [file objectForKey:@"linkURL"] ;
CGRect frame = CGRectZero;
frame.size = buttonImage.size;
button.frame = frame;
NSString *name = [file objectForKey:@"name"];
NSString *description = [file objectForKey:@"description"];
//Create Box
}
}
}
- (void) openBrowser:(id)sender {
if ([sender isKindOfClass:[MyButton class]]) {
[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[(MyButton *)sender urlString]]];
}
}
答案 1 :(得分:3)
标签是一种int类型。所以你不能在这里存储NSString URL。您需要在其他地方存储URL,可能在NSMutableArray中。将索引i存储在按钮的标记中,并将URL存储在位置i的NSMutableArray中。然后在按钮处理程序中使用标记作为索引从该NSMutableArray获取URL。
与问题无关,你没有发布_json NSArray。所以你在泄漏记忆。而且您也不需要测试if ([_json count] > 0)
。你的for循环已经处理了。