简体   繁体   中英

Load url selected object in UIWebView (iOS)

I want to open a UIWebView with a url based on the index of a custom object from an array. When I tap a button, based upon the index of objects in an array, I need for the UIWebView to open up that particular url. The problem is that when I open the webview, it will only load the url of the first object (at index 0) in the array. Here is my code:

.m:

//Here's a snippet of my viewDidLoad method.

    -(void)viewDidLoad{

    [super viewDidLoad];

buyButton = [[UIButton alloc]init];
            buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
            buyButton.frame = CGRectMake(228, 8, 25, 25);
            [buyButton setBackgroundImage:[UIImage imageNamed:@"buy-now.png"] forState:UIControlStateNormal];
            [buyButton addTarget:self action:@selector(buyBttnPressed:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:buyButton];

                 int count = [self->myArray count];
                 for (int index = 0; index < count; index++)
               {
                     DomainModel *eachObject = [self->myArray objectAtIndex:buyButton.tag];
                     buyButton.tag = index;  

                     urlString = [NSString stringWithFormat:@"%@",eachObject.url];
                     NSLog(@"Selected index:  %d",urlString);

                }


    -(void)buyBttnPressed:(id)sender{


        UIWebView *buyView = [[UIWebView alloc] initWithFrame:CGRectMake(9,132,305,368)];
        buyView.backgroundColor = [UIColor whiteColor];
        buyView.scalesPageToFit = YES;
        buyView.delegate = self;
        [self.view addSubview:buyView];

        UIButton *cancelBttn = [[UIButton alloc]init];
        cancelBttn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBttn.frame = CGRectMake(3, 5, 25, 25);
        [cancelBttn setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
        [buyView addSubview:cancelBttn];


     [buyView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];

    }

How do I fix the loop so that when the buyBttn is pressed, the the url associated with the associated index loads?

it seems that if you call this code on buyBtnPressed, then the TAG of the button will be set to the self.myArray.count -1 always (you're looping but setting it always on the same button). so current will always point to the same item - the last one in the list. i think this:

int i = 0;
for (MyObject *obj in self->myArray)
{

    i++;
    btn.tag = i;      

 }

should be done on viewDidLoad, or wherever you fill your array in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM