HTML 从一个 ViewController 到另一个 Webview 的文本

HTML text from one ViewController to another's Webview

目的:在viewcontroller1的text field press button中写一些html代码,结果显示在viewcontroller2的webview中 这是我到目前为止写的

#import <UIKit/UIkit.h>
#import <Foundation/Foundation.h>

    @interface vc1 : UIViewController

        @property (weak, nonatomic) IBOutlet UIButton * btn;
        @property (weak, nonatomic) IBOutlet UITextField * tf; 

文本字段可以只是一个标准的,我需要做的就是确保 当用户点击按钮时,vc2 出现在它的 HTML 部分 是我从文本字段中得到的字符串 下面提到了负责此操作的方法

 -(IBAction) btnAction : (id) sender;

    @end

    @interface vc2 : UIViewController

        @property (weak, nonatomic) IBOutlet UIWebView * wv;

    @end

//没有找到vc1的标准实现 //vc1

的尝试实现
@implementation vc1
@synthesize btn, tf;
-(id) initWithNibName: (NSString *)nibName0rNil bundle: (NSBundle *)nibBundle0rNil{
    self = [super initWithNibName: nibName0rNil bundle: nibBundle0rNil];
    if(self){
        //custom init
    }
    return self;
}

-(IBAction) btnAction : (id) sender {
    //initialize vc2? it's a class so i can't call it.
    //can i save the contents of the object as a NSString? or can i just give the Webview a textfield object to show as HTML?


 }

@end

@implementation vc2
@synthesize wv;

-(id) initWithNibName: (NSString *)nibName0rNil bundle: (NSBundle *)nibBundle0rNil{
    self = [super initWithNibName: nibName0rNil bundle: nibBundle0rNil];
    if(self){
        //custom init
    }
    return self;
}

-(void)viewDidLoad{
    [super viewDidLoad];

这是我应该告诉它从 vc1 中获取文本并将其显示为 HTML

的地方
[wv loadHTMLString:@"<html><body>YOUR-TEXT-HERE</body></html>" baseURL:nil]

类似的东西,但字符串被替换为插入到 vc1 的文本字段中的内容 }

-(void)viewDidUnload{
    [self setWebview: nil];
    [super viewDidUnload];
}

-(BOOL)shouldAutorotateToTinterfaceOrientation:(UIInterfaceOrientation)interfaveOrientation{
    return interfaceOrientation == UIInterfaceOrientationPortrait;
}

@end

编辑:感谢您发帖,这个社区非常有帮助。

vc2.h 的接口中声明一个 属性 就像

@property (strong, nonatomic) NSString *htmlString;

vc1.h 文件或 vc1.h 添加

#import "vc2.h"

现在在按钮动作中使用以下代码:

-(IBAction) btnAction : (id) sender {
    //initialize vc2? it's a class so i can't call it.
    //can i save the contents of the object as a NSString? or can i just give the Webview a textfield object to show as HTML?
   //With Xib 
     vc2 *secondVC =[[vc2 alloc]initWithNibName:@"vc2" bundle:nil];
     secondVC.htmlString = self.tf.text;//textField property name
    [self.navigationController pushViewController:secondVC animated:YES];
 }

最后在 vc1.m 中显示 WebView 使用:

NSString *myHTMLString = [[NSString alloc] initWithFormat:@"%@", self.htmlString];
[self.wv loadHTMLString:myHTMLString baseURL:nil];

希望这对您有所帮助。如果有任何具体错误,请告诉我。

在Swift

let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController

secondViewController.myStringValue = myTextField.text
self.navigationController?.pushViewController(secondViewController, animated: true)

在secondViewController的viewDidload方法中加载webview