I click the button to go to another Webview. However, I removed the bounce from the moved Webview, but it does not work.
First WKWebView
var openSecondScreen : SecondWebViewController!
var preloadCheck = false
...
func openSecondScreen(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
openSecondScreen = storyboard.instantiateViewController(withIdentifier: "SecondWebViewController") as! SecondWebViewController
openSecondScreen.delegate = self
openSecondScreen.loadViewIfNeeded()
openSecondScreen.secondWKWebView.navigationDelegate = self
preloadCheck = true
}
....
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if preloadCheck {
self.navigationController?.pushViewController(openSecondScreen, animated: true)
preloadCheck = false
}
}
Second WKWebView
#IBOutlet var secondWKWebView: WKWebView!
...
override func loadView() {
super.loadView()
secondWKWebView.uiDelegate = self
secondWKWebView.navigationDelegate = self
secondWKWebView.scrollView.delegate = self
...
}
extension SecondWebViewController: UIScrollViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("scrollViewDidScroll")
scrollView.bounces = false
}
}
Scroll does not display the log. Therefore, the function does not work either.
Editing: I don't think I wrote this down in advance. I'm even setting it up in advance.But it didn't work
override func viewDidLoad() {
super.viewDidLoad()
secondWKWebView.scrollView.bounces = false
}
Thanks in advance
Related
I just recently migrated my iOS UIWebview objective-c to WKWebkit swift, the problem am facing now is how to hide the scroll bar from the website I loaded. I have tried anything but not of it work, please can anyone help me out.
I have followed this step here How to hide scrollbar in WebView?, both the question and accepted answer but it didn't work for me.
Please I know this might be a duplicate question but have I have tried many post to solve this none work.
var lastOffsetY :CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
webViewSetup()
}
In webViewSetup
func webViewSetup(){
webView.scrollView.delegate = self
}
In viewWillAppear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let scrollView = webView.subviews[0] as? UIScrollView
webView.scrollView.contentSize = CGSize(width: webView.frame.size.width, height: webView.scrollView.contentSize.height)
scrollView?.bounces = false
scrollView?.decelerationRate = .fast
scrollView?.showsHorizontalScrollIndicator = false
webView.scrollView.showsHorizontalScrollIndicator = false
webView.scrollView.showsVerticalScrollIndicator = false
webView.scrollView.alwaysBounceHorizontal = false
webView.scrollView.bounces = false
}
In scrollViewDidScroll
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.frame.size.height) {
scrollView.setContentOffset(CGPoint(x:scrollView.contentOffset.x, y:scrollView.contentSize.height - scrollView.frame.size.height), animated: false)
}
}
//FIXING SCROLL VIEW
//Delegate Methods
func scrollViewWillBeginDragging(_ scrollView: UIScrollView){
lastOffsetY = scrollView.contentOffset.y
}
//FIXING SCROLL VIEW
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView){
let hide = scrollView.contentOffset.y > self.lastOffsetY
self.navigationController?.setNavigationBarHidden(hide, animated: true)
}
To turn off the web view's scrolling:
webView.scrollView.isScrollEnabled = false
If the code you provided is only for turning off the scrollview, that code can largely be culled down to something like this:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
//configure webView
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.scrollView.isScrollEnabled = false
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: "https://www.stackoverflow.com") {
webView.load(URLRequest(url: url))
}
}
}
I am new to swift and ios.The View Controller launch always the same link and do do not show the grid menu with buttons that is in second scene.What i am doing wrong here?
I have in main.storyboard three scene.
In the first scene is navigation.The second scene is a grid menu with buttons that depending on the button click will open a link in webview located in the 3rd scene.The third scene includes a view that should open a specific link depending on the click button in step 2
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView : WKWebView!
var webi:String = "https://www.google.al"
override func viewDidLoad() {
print("‼️OMG:viewDidLoad", webi)
super.viewDidLoad()
let url = URL(string: webi)!
webView.load(URLRequest(url: url))
let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
toolbarItems = [refresh]
navigationController?.isToolbarHidden = false
}
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
#IBAction func Menu1(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1")
webi = "https://www.menu1.com"
}
#IBAction func Menu2(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1")
webi = "https://www.menu2.com"
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
}
}
Your problem is that you change the urlStr webi without reloading the webview again
func refresh() {
let url = URL(string: webi)!
webView.load(URLRequest(url: url))
}
#IBAction func Menu1(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1")
webi = "https://www.menu1.com"
self.refresh()
}
#IBAction func menu2(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1") // other link
webi = "https://www.menu1.com"
self.refresh()
}
///
Navigation->buttons Menu VC -> webViewVC
while your are in buttons menu
let vc = ViewController()
vc.webi = "" // set link according to the clicked button
self.navigationController?.pushViewController(vc,animated:true)
Look to this Demo
Is it possible to detect a back swipe in a web view when there has not been any forward navigation? The following code works fine if the user has moved off the first page but I want to know if they back swiped while on that page.
Update - This is the code I'm using after modifying it per comments. I added the navigation back function and the swipe gesture.
class WebViewClient: UIViewController, WKUIDelegate, WKNavigationDelegate, UIGestureRecognizerDelegate
{
var webView: WKWebView!
public func load(pageLink page: String)
{
print("Opening: " + page)
if webView != nil
{
if let myURL = URL(string:page)
{
webUrlRequest = page
let myRequest = URLRequest(url: myURL)
webView.load(myRequest)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
{
print("Opened: " + webUrlRequest)
}
override func loadView()
{
let pref = WKPreferences()
pref.javaScriptEnabled = true
let config = WKWebViewConfiguration()
config.preferences = pref
webView = WKWebView(frame: .zero, configuration: config)
webView.uiDelegate = self
webView.navigationDelegate = self
webView.allowsBackForwardNavigationGestures = true
view = webView
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void)
{
if navigationAction.navigationType == .backForward && webView.backForwardList.backList.count == 0
{
print("Can't go back any more")
}
decisionHandler(.allow)
}
#objc func backNavigationFunction(_ sender: UIScreenEdgePanGestureRecognizer)
{
let dX = sender.translation(in: view).x
if sender.state == .ended
{
let fraction = abs(dX / view.bounds.width)
if fraction >= 0.35
{
print("Back swipe")
//back navigation code here
}
}
}
override func viewDidLoad()
{
super.viewDidLoad()
let swipeGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(backNavigationFunction(_:)))
swipeGesture.edges = .left
swipeGesture.delegate = self
webView.addGestureRecognizer(swipeGesture)
}
}
I would implement a UIScreenEdgePanGestureRecognizer to handle this. Add the following to your viewDidLoad
let swipeGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(backNavigationFunction(_:)))
swipeGesture.edges = .left
swipeGesture.delegate = self
view.addGestureRecognizer(swipeGesture)
Then, implement a function to handle the backNavigationFunction like below:
#objc func backNavigationFunction(_ sender: UIScreenEdgePanGestureRecognizer) {
let dX = sender.translation(in: view).x
if sender.state == .ended {
let fraction = abs(dX / view.bounds.width)
if fraction >= 0.35 {
//back navigation code here
}
}
}
Don't forget to make the ViewController inherit from the UIGestureRecognizerDelegate class (i.e. class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, UIGestureRecognizerDelegate). The delegate in question here is UIGestureRecognizerDelegate but I anticipate you'll need the others as well.
I am new to IOS. I am trying to implement activity indicator while loading web view, but I am unable to do that.While debugging I encounter that animator is starting but it is not getting visible. I am using swift 3. Here my code is as below.Please let me know what I am doing wrong. If anyone have good resource to learn about activity indicator please mention that also.
class ViewController: UIViewController,UIWebViewDelegate {
var WebView: UIWebView!
override func viewDidLoad()
{
super.viewDidLoad()
WebView = UIWebView(frame: UIScreen.main.bounds)
WebView.delegate = self
view.addSubview(WebView)
if let url = URL(string: "https://apple.com")
{
let request = URLRequest(url: url)
WebView.loadRequest(request)
}
activityindicator.startAnimating()
activityindicator.color = UIColor.black
activityindicator.alpha = 1
activityindicator.isHidden = false
}
// weak var activityindicator: UIActivityIndicatorView!
let activityindicator = UIActivityIndicatorView()
func webViewDidStartLoad(_ webView: UIWebView)
{
activityindicator.startAnimating()
activityindicator.color = UIColor.black
activityindicator.alpha = 1
activityindicator.isHidden = false
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activityindicator.stopAnimating()
activityindicator.alpha = 0
activityindicator.isHidden = true
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError)
{
activityindicator.isHidden = true
}
}
Looks like the activity indicator is not added to view. Similar to how we are adding webview, center and add the indicator in viewDidLoad (code below).
activityindicator.center = self.view.center
view.addSubview(activityindicator)
Also I would suggest moving the global declarations to one place. i.e move the indicator declaration let activityindicator = UIActivityIndicatorView(), to be below webview's on top, instead of middle of class. This helps in quick readability.
Here is your full code. Now it's working -
import UIKit
class ViewController: UIViewController,UIWebViewDelegate {
var WebView: UIWebView!
override func viewDidLoad()
{
super.viewDidLoad()
WebView = UIWebView(frame: UIScreen.main.bounds)
WebView.delegate = self
view.addSubview(WebView)
if let url = URL(string: "https://apple.com")
{
let request = URLRequest(url: url)
WebView.loadRequest(request)
}
activityindicator.startAnimating()
activityindicator.center = self.view.center
view.addSubview(activityindicator)
activityindicator.color = UIColor.black
activityindicator.alpha = 1
}
// weak var activityindicator: UIActivityIndicatorView!
let activityindicator = UIActivityIndicatorView()
func webViewDidStartLoad(_ webView: UIWebView)
{
activityindicator.startAnimating()
activityindicator.color = UIColor.black
activityindicator.alpha = 1
activityindicator.isHidden = false
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activityindicator.stopAnimating()
activityindicator.alpha = 0
activityindicator.isHidden = true
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError)
{
activityindicator.isHidden = true
}
}
I've been having trouble getting a WKWebView in Swift to trigger some javascript in the loaded web page. Im just trying to use javascript to change a background color on the website if the user swipes left, swipes right, or clicks a button. Any help is greatly appreciated.
import UIKit
import WebKit
class myViewController: UIViewController, WKNavigationDelegate {
#IBOutlet var container: UIView!
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
self.webView = WKWebView()
container.addSubview(webView!)
webView?.allowsBackForwardNavigationGestures = true
webView?.navigationDelegate = self
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(myViewController.handleSwipes(_:)))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(myViewController.handleSwipes(_:)))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
override func viewDidAppear(animated: Bool) {
let frame = CGRectMake(0, 0, container.bounds.width, container.bounds.height)
webView!.frame = frame
let url = NSURL(string: "https://www.google.com")
let request = NSURLRequest(URL: url!)
self.webView!.loadRequest(request)
}
#IBAction func buttonClick(sender: AnyObject) {
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='red';", completionHandler: nil)
}
func handleSwipes(sender:UISwipeGestureRecognizer){
if (sender.direction == .Left){
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='black';", completionHandler: nil)
}
if (sender.direction == .Right){
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='green';", completionHandler: nil)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='red';", completionHandler: nil)
}
}
You misspelled the Javascript's function name. It should be getElementById instead of getElementByID:
document.getElementById('hplogo').style.backgroundColor = '...'