I am trying to get an animated gif to play in the background, and have some labels and buttons appear on top. This code runs and shows the animated gif, however it does not show the buttons or label text.
import Foundation
import UIKit
import WebKit
class LoginViewController: UIViewController {
#IBOutlet var containerView: UIView! = nil
var webViewBG: WKWebView?
#IBOutlet weak var loginButton: UIButton!
#IBOutlet weak var signUpButton: UIButton!
override func loadView() {
super.loadView()
self.webViewBG = WKWebView()
self.view = self.webViewBG
}
override func viewDidLoad() {
super.viewDidLoad()
let htmlPath = Bundle.main.path(forResource: "WebViewContent", ofType: "html")
let htmlURL = URL(fileURLWithPath: htmlPath!)
let html = try? Data(contentsOf: htmlURL)
var req = NSURLRequest(url:htmlURL)
self.webViewBG!.load(req as URLRequest)
webViewBG?.isUserInteractionEnabled = false;
self.loginButton.layer.borderColor = UIColor.white.cgColor
self.loginButton.layer.borderWidth = 2
self.signUpButton.layer.borderColor = UIColor.white.cgColor
self.signUpButton.layer.borderWidth = 2
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
}
It looks like this line overrides your view controller's view where the buttons are:
self.view = self.webViewBG
Try
self.view.addSubview(self.webViewBG)
You might also need to tweak the z position so that the webView is located 'behind' the buttons, like this:
self.webViewBG.layer.zPosition = 0.5
Higher zPosition means the view stands out more 'towards' the user
Related
Hello and thanks for reading this,
I'm building a simple app with 2-3 tabs (view controllers), and the first one is some kind of converter (miles to km), it's fine, and the second viewcontroller has to have a "webview" element.
So, when I build a separate app with only ONE view controller, (with "import WebKit") it works fine:
super.viewDidLoad()
webview.load(URLRequest(url: URL(string: "https://www.google.com")!))
BUT when I copy this to my 2-tabbed app code under the line #super.viewDidLoad()#, it crashes saying "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value".
I'm really new with this all, so I don't know how to fix this. And I didn't find solutions to similar problem on this forum. Thank you in advance!
p.s. how am I creating web view - visually add it. I see the tip to create it by coding, I will try, thank you
p.p.s. Im adding here my code:
import UIKit
import SafariServices
import WebKit
extension String {
func toDouble() -> Double? {
return NumberFormatter().number(from: self)?.doubleValue
} }
class ViewController: UIViewController {
#IBOutlet var mileField: UITextField!
#IBOutlet var mileResult: UILabel!
#IBOutlet var meters: UILabel!
#IBOutlet var cmeters: UILabel!
#IBAction func mileButton(_ sender: UIButton) {
let mile: Double = mileField.text?.toDouble() ?? 0
let km = mile * 1.6
let m = km * 1000
let cm = m * 100
meters.text = String(m)+" m"
mileResult.text = String(km)+" km"
cmeters.text = String(cm)+" cm"
}
#IBOutlet var vw: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
vw.load(URLRequest(url: URL(string: "google.com")!)) // this is where I got Fatal error blah blah blah
}
#IBAction func bTapped() {
let vc = SFSafariViewController(url: URL(string: "https://www.apple.com")!)
present(vc, animated: true) // this works fine but I need to use webview element
}
}
a little screenshot
Declare your two view controllers. Also please assign this class names to your view controller in storyboard.
https://i.stack.imgur.com/BDoY6.png
class ViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
class ViewController2: UIViewController {
#IBOutlet var webview: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webview.load(URLRequest(url: URL(string: "https://www.google.com")!))
}
}
I'm trying to set an image as the title of a navigation bar in swift using the code below. The code builds successfully, but the image does not display. Any advice would be appreciated.
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var navigationBar: UINavigationItem!
var convoImage: UIImage!
var convoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.convoImage = UIImage(contentsOfFile: "conversation.png")
self.convoImageView = UIImageView(image: self.convoImage)
self.navigationBar.titleView = self.convoImageView
}
}
Set the navigationItem's titleView.
let image = UIImage(named: "image_name.png")
self.navigationItem.titleView = UIImageView(image: image)
In your code replace below line:
self.convoImage = UIImage(contentsOfFile: "conversation.png")
with
self.convoImage = UIImage(named: "conversation.png")
You should set convoImageView frame .
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var navigationBar: UINavigationItem!
var convoImage: UIImage!
var convoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.convoImage = UIImage(named: "conversation.png")
self.convoImageView = UIImageView(image: self.convoImage)
self.convoImageView.frame = CGRectMake(0,0,720,100)
self.navigationBar.titleView = self.convoImageView
}
}
I have loaded a webpage to xcode WebView. But only the upper portion of the page is loaded. I can not scroll down to the bottom of the page. Same fact for pdf. Only upper 2 pages can be scrolled. What can i do ?Here is my code.
Thanks in advance.
import UIKit
class ViewController: UIViewController {
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
var URL = NSURL(string: "http://www.archetapp.com")
webView.loadRequest(NSURLRequest(URL: URL!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//for pdf
import UIKit
class ViewController: UIViewController {
#IBOutlet var webViews: UIWebView!
var path = ""
override func viewDidLoad() {
super.viewDidLoad()
path = NSBundle.mainBundle().pathForResource("ibook", ofType: "pdf")!
let url = NSURL.fileURLWithPath(path)
webViews.scalesPageToFit = true
webViews.scrollView.scrollEnabled = true
webViews.userInteractionEnabled = true
self.webViews.loadRequest(NSURLRequest(URL: url!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Try this!
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet var webView : UIWebView
override func viewDidLoad() {
super.viewDidLoad()
//load initial
path = NSBundle.mainBundle().pathForResource("ibook", ofType: "pdf")!
let url = NSURL.fileURLWithPath(path)
var req = NSURLRequest(URL : url)
webView.delegate = self // <---
webView.loadRequest(req)
}
func webViewDidStartLoad(webView : UIWebView) {
//UIApplication.sharedApplication().networkActivityIndicatorVisible = true
println("webViewDidStartLoad")
}
func webViewDidFinishLoad(webView : UIWebView) {
//UIApplication.sharedApplication().networkActivityIndicatorVisible = false
webViews.scalesPageToFit = true
webViews.scrollView.scrollEnabled = true
webViews.userInteractionEnabled = true
println("webViewDidFinishLoad")
}
}
I had the same issue just today and at least in my case it was caused by having the "Scale Pages to Fit" option checked in the WebView properties. I'm assuming Carlos' reply regarding the zoom scale fixes it anyways but I didn't need the option enabled in the first place so that was my easy fix.
I want to have a UIScrollView of UIViewControllers. I tested the ScrollView and it works fine, except when I try to add the ViewControllers. The project builds fine, but I get a "fatal error: unexpectedly found nil while unwrapping an Optional value" error that points at the ViewController, particularly the line:
self.imageView.image = UIImage(named: self.image!)
However, when I inspect the object, I can see variables image and text have values in the ViewController. I'm using Xcode 6.3 Beta and building to iOS8.1 target.
Here's the code:
import UIKit
class ViewController: UIViewController {
//#IBOutlet weak var contentScrollView: UIScrollView!
#IBOutlet var contentScrollView: UIScrollView!
//test to make sure ScrollView functions
//let colors = [UIColor.redColor(),UIColor.blueColor(), UIColor.greenColor(), UIColor.whiteColor(), UIColor.blackColor(), UIColor.yellowColor()]
var frame = CGRectMake(0, 0, 0, 0)
var dataArray = [PostItem]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var da = PostItem(text: "test 1", pic: "beans.jpg")
self.dataArray.append(da!)
da = PostItem(text: "test 2", pic: "coffee.jpg")
self.dataArray.append(da!)
da = PostItem(text: "test 3", pic: "coffeeCup.jpg")
self.dataArray.append(da!)
for index in 0..<self.dataArray.count{
self.frame.origin.y = self.contentScrollView.frame.size.height * CGFloat(index)
self.frame.size = self.contentScrollView.frame.size
self.contentScrollView.pagingEnabled = false
let tempPost = self.dataArray[index]
var vc = PostViewController()
vc.text = tempPost.postText
vc.image = tempPost.postImage
self.contentScrollView.addSubview(vc.view)
}
self.contentScrollView.contentSize = CGSizeMake(self.view.frame.size.width, CGFloat(self.dataArray.count) * self.contentScrollView.frame.height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
And here is the code for the ViewController I want to add:
import UIKit
class PostViewController: UIViewController {
//let postItem
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var postToFBButton: UIButton!
#IBOutlet weak var postToTwitterButton: UIButton!
#IBOutlet weak var postText: UILabel!
var image:String?
var text:String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.imageView.image = UIImage(named: self.image!)
self.postText.text = text!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
The fix is to create the PostViewController through instantiateViewControllerWithIdentifier from storyboard, this way, it will have an imageView loaded from storyboard when its view is added to the scrollview.
I'm playing around with Swift to learn it and right now I'm having trouble getting the text from a UISearchBar
Right now my code looks like this:
import UIKit
class SecondViewController: UIViewController {
#IBOutlet var myWebView : UIWebView
#IBOutlet var adressbar: UISearchBar
override func viewDidLoad() {
super.viewDidLoad()
adressbar.showsScopeBar = true
var url = NSURL(string: "http://google.com")
var request = NSURLRequest(URL: url)
myWebView.scalesPageToFit = true
myWebView.loadRequest(request)
}
func searchBarSearchButtonClicked( searchBar: UISearchBar!) {
var url = NSURL(string: adressbar.text)
var request = NSURLRequest(URL: url)
myWebView.scalesPageToFit = true
myWebView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
In viewDidLoad you must set the delegate of the search bar to be receiving searchBarSearchButtonClicked from it:
import UIKit
class SecondViewController: UIViewController, UISearchBarDelegate
{
#IBOutlet var myWebView : UIWebView
#IBOutlet var adressbar: UISearchBar
override func viewDidLoad()
{
super.viewDidLoad()
adressbar.showsScopeBar = true
adressbar.delegate = self
var url = NSURL(string: "http://google.com")
var request = NSURLRequest(URL: url)
myWebView.scalesPageToFit = true
myWebView.loadRequest(request)
}
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
var url = NSURL(string: searchBar.text)
var request = NSURLRequest(URL: url)
myWebView.scalesPageToFit = true
myWebView.loadRequest(request)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
Simple (non-specific) answer for those arriving here via search:
If your outlet name for your UISearchBar is 'searchBar'...
#IBOutlet weak var searchBar: UISearchBar!
Then the text entered by the user in UISearchBar is called...
searchBar.text
Two common things Swift coders forget:
1. Make sure to add UISearchBarDelegate class...
ViewController: UIViewController, UISearchBarDelegate
Don't forget to identify your view class as the delegate...
Inside viewDidLoad you could write...
searchBar.delegate = self
If you forget #1 above you won't be able to auto-complete the methods you'll need to implement like...
func searchBarSearchButtonClicked(_ seachBar: UISearchBar) { your code }
... which is given to you by the delegate protocol.
1.First thing is to conform to the UISearchbarDelegate.
2.Set the search bar delegate to self.
You can find more on this here Swift iOS tutorial : Implementing search using UISearchBar and UISearchBarDelegate