将Tableview单元格的文本传递给RootViewController

时间:2014-03-31 20:27:24

标签: ios iphone objective-c uitableview

我是iOS编程的新手。我已经阅读了关于这个问题的线索,但也无法弄清楚究竟是什么导致了这个错误。我需要将第一个tableview单元格的bookmarkViewController的tableview文本传递回myViewController的URL地址栏,当我点击第一个tableview的单元格时,它是根ViewController。 除了传递到根ViewController的数据之外,一切正常,我正在使用委托。

myViewController.h

#import "bookmarkViewController.h"
#import <UIKit/UIKit.h>
#import "historyViewController.h"
#import "AppDelegate.h"
#import "Reachability.h"

@interface myViewController : UIViewController <UITextFieldDelegate,UIAlertViewDelegate,secondViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UIBarButtonItem *addButton;

@property (weak, nonatomic) IBOutlet UITextField *addressBar;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UITextField *searchBar;
- (IBAction)goBack:(id)sender;
- (IBAction)goForward:(id)sender;
- (IBAction)refreshWebView:(id)sender;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *goBackButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *goForwardButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *refreshButton;
-(void)textFieldDidEndEditing:(UITextField *)textField;




- (void) loadWebPageFromString:(NSString *)string;


@end

myViewController.m

   #import "myViewController.h"


    @interface myViewController ()

    @end

    @implementation myViewController



    -(void)loadView
    {


        [super loadView];
        [_goBackButton setEnabled:NO];

    }

    - (void)webViewDidFinishLoad:(UIWebView *)webview
    {


        _addButton.enabled=YES;
        _refreshButton.enabled=YES;
        if ([_webView canGoBack]) {
            [_goBackButton setEnabled:YES];

        } else [_goBackButton setEnabled:NO];

        if ([_webView canGoForward]) {
            [_goForwardButton setEnabled:YES];

        } else _goForwardButton.enabled=NO;


    }

    - (void)checkForWIFIConnection {
        Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];

        NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

        if (netStatus!=ReachableViaWiFi)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection"
                                                            message:@"Your device is not connected to internet."
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];



        }
    }







    - (void)viewDidLoad
    {

        _refreshButton.enabled=NO;
        _addButton.enabled=NO;
        [_goBackButton setEnabled:NO];
        _goForwardButton.enabled=NO;
        [self checkForWIFIConnection];

        [super viewDidLoad];
        }


    -(void)textFieldDidEndEditing :(UITextField *)textField
    {


        if (textField.text){

            if (textField==_searchBar){

                AppDelegate *historydelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
                NSMutableArray *a=historydelegate.historyArray;
                NSString *b=[NSString stringWithFormat:@"http://www.google.com/search?q=%@",textField.text] ;
                [a addObject:b];

            }}}



    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }


    - (IBAction)googleEntered:(UITextField *)sender {


        Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];

        NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

        if (netStatus==ReachableViaWiFi){
            [self loadWebPageFromString:_searchBar.text];
            [self textFieldDidEndEditing:_searchBar];
            _addressBar.text=[NSString stringWithFormat: @"http://www.google.com/search?q=%@",_searchBar.text] ;
        }else {[self checkForWIFIConnection];self.addressBar.text=NULL;}


    }


    - (IBAction)goBack:(id)sender {
        [_webView goBack];

        _searchBar.text=NULL;
        _addressBar.text=NULL;
    }

    - (IBAction)goForward:(id)sender {
            [_webView goForward];
        _searchBar.text=NULL;

    }

    - (IBAction)refreshWebView:(id)sender {
        [_webView reload];


        [self checkForWIFIConnection];


    }


    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

        AppDelegate *maindelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
        NSMutableArray *a=maindelegate.bookmarksArray;
            if([segue.identifier isEqualToString:@"segueOne"]){

                if ([_addressBar.text length]!=0){
                    NSString *b=[NSString stringWithFormat:@"%@",_addressBar.text];
                    [a addObject:b];



                }}}

        - (void) loadWebPageFromString:(NSString *)string {
        NSURL *url = [NSURL URLWithString:string];





            NSString *googleSearch = [string stringByReplacingOccurrencesOfString:@" " withString:@"+"];
            url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", googleSearch]];
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
            [_webView loadRequest:request];
        }


    -(void)loadAddress:(NSString *)mystring{

            NSURL *myurl = [NSURL URLWithString:mystring];
        if(!myurl.scheme){
        myurl = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", mystring]];

        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:myurl];
        [_webView loadRequest:request];}
        else{
            myurl = [NSURL URLWithString:[NSString stringWithFormat:@"%@", mystring]];

            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:myurl];
            [_webView loadRequest:request];

        }

            }


    -(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{



        if (navigationType==UIWebViewNavigationTypeLinkClicked) {

            NSURL *URL=[request URL];

                    [self checkForWIFIConnection];
            if ([URL scheme] ) {
                Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];

                NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

                if (netStatus==ReachableViaWiFi ){
                    _addressBar.text=URL.absoluteString;
                    _searchBar.text=NULL;
                    [_webView loadRequest:request];
                    AppDelegate *historydelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
                    NSMutableArray *a=historydelegate.historyArray;
                    [a addObject:URL.absoluteString];
                }




            }
            return NO;
        }
        return YES;

    }

    - (BOOL) urlIsValid: (NSString *) url
    {
        NSString *regex =
        @"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
        /// OR use this
        ///NSString *regex = "(http|ftp|https)://[\w-_]+(.[\w-_]+)+([\w-.,@?^=%&:/~+#]* [\w-\@?^=%&/~+#])?";
        NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

        if ([regextest evaluateWithObject: url] == NO) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid URL"
                                                            message:@"Enter valid URL."
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }

        return [regextest evaluateWithObject:url];
    }

    -(IBAction)addressEntered:(UITextField *)sender {
            Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];

        NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

        if (netStatus==ReachableViaWiFi && [self urlIsValid:_addressBar.text]){



        [self loadAddress:_addressBar.text];
            AppDelegate *historydelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
            NSMutableArray *a=historydelegate.historyArray;

            [a addObject:_addressBar.text];

        }else [self checkForWIFIConnection];
        [sender resignFirstResponder];
        _searchBar.text =NULL;

    }
    -(void)showView{
    bookmarkViewController *b=[[bookmarkViewController alloc]initWithNibName:@"bookmarkViewController" bundle:nil];

    b.delegate=self;

    [self presentViewController:b animated:YES completion:nil];

}
    - (void)passData:(NSString *)data
    {


        self.addressBar.text=data;

        }
    - (IBAction)go:(id)sender {
    [self showView];
}

    @end

bookmarkViewController.h

@protocol secondViewControllerDelegate <NSObject>

@required

- (void)passData:(NSString *)data;

@end


#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "myViewController.h"
@interface bookmarkViewController : UIViewController 
@property (nonatomic, weak) id<secondViewControllerDelegate> delegate;
@property (weak, nonatomic) IBOutlet UITableView *tableView;


- (IBAction)goBac:(id)sender;



@end

bookmarkViewController.m

#import "bookmarkViewController.h"
#import "AppDelegate.h"
@interface bookmarkViewController ()

@end

@implementation bookmarkViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.

    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    AppDelegate *maindelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
    NSMutableArray *a=[maindelegate bookmarksArray];
    cell.textLabel.text = [a objectAtIndex:[indexPath row]];
    return cell;


}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
              if ([indexPath row]==0) {

           if ([self.delegate respondsToSelector:@selector(passData:)]) {


               [self.delegate passData:cell.textLabel.text];


              }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    AppDelegate *maindelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
    NSMutableArray *a=[maindelegate bookmarksArray];
    return [a count];
}


- (void)viewDidLoad
{



   [super viewDidLoad];
    [[self tableView] reloadData];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)goBac:(id)sender {

    [self dismissViewControllerAnimated:YES completion:nil];
    }
@end

ScreenShot

2 个答案:

答案 0 :(得分:1)

选择行时,您不应使用dequeueReusableCellWithIdentifier:方法。只有当您想要实际获得可重用的单元格时才应该使用它。您可以使用:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];

    if ([indexPath row]==0)
    {
        if ([self.delegate respondsToSelector:@selector(passData:)])
        {
            [self.delegate passData:cell.textLabel.text];
        }
    }
}

您不应该从子视图控制器调用dismissViewControllerAnimated:completion:方法,它是父视图控制器的工作。 在您的委托方法中:

- (void) passData:(NSString *)data
{
    self.addressBar.text = data;
    [self dismissViewControllerAnimated:YES completion:nil];
}

编辑:方法名称已更新。

答案 1 :(得分:0)

Another way to do same is by using navigation controller stack if your application is navigation based.
Try this:- 

1.Define a global NSString in MyViewController.h like
@property(strong, nonatomic) NSString *strText;

2.Do following code on didSelectRowAtIndexPath of BookMarkViewController

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if(indexPath.row == 0)
    {
        NSArray *arrControllers = [self.navigationController.viewControllers];
        MyViewController *objMyCnrl = [arrControllers objectAtIndex:[arrControllers count]-2];
        objMyCnrl.strText = cell.textLabel.text; // Pass the string value here
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
相关问题