简体   繁体   English

按下按钮即可更改UIWebView中的文本。 (简单?)

[英]Changing text in UIWebView with the press of a button. (simple?)

How can I change the text in a WebView, with the press of a button? 如何通过按下按钮来更改WebView中的文本?

I have a Web View, populated with HTML. 我有一个用HTML填充的Web视图。

if ([buttonState isEqualToString:@"YES"]) {
    UIFont *webFont = [UIFont fontWithName:@"Helvetica" size:12];
    NSString *mainTextString;
    mainTextString = @"<p><b>General:</b>THIS IS TEXT1</p>";
    mainTextString = [NSString stringWithFormat:@"<span style=\"font-family: %@; font-size: %i\">%@</span>", webFont.fontName, (int) webFont.pointSize, mainTextString];
    [mainText loadHTMLString:mainTextString baseURL:nil];
}
else if ([buttonState isEqualToString:@"NO"]) {
    UIFont *webFont = [UIFont fontWithName:@"Helvetica" size:12];
    NSString *mainTextString;
    mainTextString = @"<p><b>General:</b>THIS IS TEXT2</p>";
    mainTextString = [NSString stringWithFormat:@"<span style=\"font-family: %@; font-size: %i\">%@</span>", webFont.fontName, (int) webFont.pointSize, mainTextString];
    [mainText loadHTMLString:mainTextString baseURL:nil];
}

I also have a UIButton, with which I want to change the text in the Webview. 我还有一个UIButton,我想用它来更改Webview中的文本。

- (IBAction)textChangeButton:(id)sender {
    if ([buttonState isEqualToString: @"NO"]) {
        buttonState = @"YES";
    }
    else if ([buttonState isEqualToString:@"YES"]) {
        buttonState = @"NO";
    }
    [mainText reload];
}

Unfortunately, when I press the button the second text does not appear! 不幸的是,当我按下按钮时,第二个文本没有出现!

Being fairly new to programming, I have no idea what the problem is. 作为编程新手,我不知道问题出在哪里。 I have tried reloading the webview in the button press - still no luck. 我尝试在按钮按下时重新加载Webview-仍然没有运气。 Could someone point me in the right direction? 有人可以指出我正确的方向吗?

Any help is much appreciated! 任何帮助深表感谢!

Calling [mainText reload] will just load an empty page. 调用[mainText reload]只会加载一个空白页面。 You need to execute the first code again for the webview to load the correct content. 您需要再次执行第一个代码以使Web视图加载正确的内容。

Try to move the code to a new method and call it in viewDidLoad and textChangeButton: 尝试将代码移至新方法,然后在viewDidLoadtextChangeButton:调用textChangeButton:

- (void)reloadWebPage {
    if ([buttonState isEqualToString:@"YES"]) {
        mainTextString = (...);
        [mainText loadHTMLString:mainTextString baseURL:nil];
    }
    else if ([buttonState isEqualToString:@"NO"]) {
        mainTextString = (...);
        [mainText loadHTMLString:mainTextString baseURL:nil];
    }
}

- (void)viewDidLoad {
    [self reloadWebPage];
}

- (IBAction)textChangeButton:(id)sender {
    if ([buttonState isEqualToString: @"NO"]) {
        buttonState = @"YES";
    }
    else if ([buttonState isEqualToString:@"YES"]) {
        buttonState = @"NO";
    }

    [self reloadWebPage];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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