在UIWebView中添加UIButton
我有一个UIWebView,它已经被我的请求(loadRequest)填充。在UIWebView中添加UIButton
我想在其中添加一个UIButton。这很容易写这个简单的代码:
[self.myWebView loadRequest:request];
[self.myWebView addSubview:myButton];
但是,它似乎是的UIButton不会与UIWebView中的内容滚动。它保持像UIWebView顶层的固定状态。所以当用户滚动时,UIButton会与内容不同步。
任何想法?
你可以注入HTML标记,如 < A HREF = 'yourTag01' > <按钮>我的按钮< /按钮> </A > 到使用stringByEvaluatingJavaScriptFromString方法您的UIWebView的内容。
捕获点击事件,并防止其重新加载网页视图的内容使用此委托:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if(navigationType==UIWebViewNavigationTypeLinkClicked && [[request.URL absoluteString] isEqualToString: @"yourTag01"])
{
//your custom action code goes here
return NO;
}
return YES;
}
似乎是一个有趣的解决方案。我会明天尝试这个,让你知道,谢谢;) – 2011-06-14 22:54:57
它的工作,谢谢:)我做这个方法的问题是重新加载的UIWebView(使用js帧)。 – 2011-06-15 08:28:23
+1非常好的答案.... – Saawan 2011-08-16 05:00:05
你不能以任何理智的直截了当的方式做到这一点。你可能想重新评估你在做什么。
在iOS 5中,您可以直接访问一个UIWebView的滚动视图,这就是你真的想添加按钮,https://developer.apple.com/documentation/uikit/uiwebview/1617955-scrollview。但我倾向于同意以前的评论者,你应该考虑一种不同的方法,因为将UIKit与Web视图混合并不真正用于描述你的描述。
继续使用axiixc的评论,下面是一些代码,您可以使用它将按钮放在webview的底部。通过在布局子视图中放置定位代码,您可以正确处理旋转。
- (void)webViewDidFinishLoad:(UIWebView *)webview{
if (!_button){
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"Move All Blue Cards to Known" forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"signin-button-blue-color"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.titleLabel.font = [UIFont boldSystemFontOfSize:16.0];
[_webview.scrollView addSubview:button];
_button = button;
}
[self setNeedsLayout];
[self layoutIfNeeded];
}
- (void)layoutSubviews{
[super layoutSubviews];
float y = 0;
CGRect originalRect = _webview.frame;
_webview.frame = CGRectMake(0, 0, originalRect.size.width, 1); // Trick the webview into giving the right size for content
CGSize contentSize = _webview.scrollView.contentSize;
_webview.frame = originalRect;
if (contentSize.height < _webview.frame.size.height){ // This keeps the button at the bottom of the webview, or at the bottom of the content, as needed.
y = _webview.frame.size.height - 64; // 44 tall + 20 offset from the bottom
} else {
y = contentSize.height + 20;
}
_button.frame = CGRectMake(20, y, self.frame.size.width-40, 44); // 40/2 = 20 px on each side
contentSize.height = CGRectGetMaxY(_button.frame)+20;
_webview.scrollView.contentSize = contentSize;
}
尝试将按钮添加到界面生成器中的web vew,或者可以减小web视图的框架大小并将按钮添加到视图。 – Sandeep 2011-06-14 17:27:54