I have a navigation controller and I want the title to have a custom font. I have tried to do this but when it runs I get Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP.subcode=0x0)
Here is my code.
import UIKit
class PriceCheckSpreadsheetViewController: UIViewController {
#IBOutlet weak var SpreadsheetView: UIWebView!
#IBOutlet weak var Loading: UIActivityIndicatorView!
#IBOutlet weak var BackButton: UIBarButtonItem!
#IBOutlet weak var ForwardButton: UIBarButtonItem!
#IBOutlet weak var NaviBar: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let url = "http://www.backpack.tf/pricelist/spreadsheet"
let requestURL = NSURL(string: url)
let request = NSURLRequest(URL: requestURL!)
SpreadsheetView.loadRequest(request)
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "TF2Build", size: 12)!]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webViewDidStartLoad(_ : UIWebView) {
Loading.startAnimating()
NSLog("Loading")
}
func webViewDidFinishLoad(_ : UIWebView) {
Loading.stopAnimating()
NSLog("Done")
if SpreadsheetView.canGoBack {
BackButton.enabled = true
}
else {
BackButton.enabled = false
}
if SpreadsheetView.canGoForward {
ForwardButton.enabled = true
}
else {
ForwardButton.enabled = false
}
}
#IBAction func Reload(sender: AnyObject) {
SpreadsheetView.reload()
}
#IBAction func Back(sender: AnyObject) {
SpreadsheetView.goBack()
}
#IBAction func Forward(sender: AnyObject) {
SpreadsheetView.goForward()
}
}
Related
I'm running into an error when transitioning to view controllers by overriding the built-in prepare() function in Swift. I have a UIImageView for backgrounds on my screens. Here is the code for two of the view controllers in question.
import UIKit
import FirebaseAuth
class HomeVC: UIViewController {
#IBOutlet weak var signOutButton: UIButton!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendsNavButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var profileNavButton: UIButton!
#IBOutlet weak var bumpButton: UIButton!
#IBOutlet weak var welcomeLabel: UILabel!
#IBOutlet weak var doNotDisturbLabel: UILabel!
#IBOutlet weak var doNotDisturbButton: UIButton!
var userName = ""
var dndIsOn: Bool = false
#IBAction func dndToggled(_ sender: Any) {
dndIsOn = !dndIsOn
User.current.available = !dndIsOn
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).updateData([Constants.Firestore.Keys.available : !dndIsOn])
if dndIsOn {
print("DND is on!")
setupDNDUI()
} else if !dndIsOn {
print("DND is off!")
setupActiveUI()
}
}
#IBAction func signOutTapped(_ sender: Any) {
let firAuth = Auth.auth()
do {
try firAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
print("Successfully signed out")
}
#IBAction func bumpTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toCall, sender: self)
}
#IBAction func friendsNavTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toFriends, sender: self)
}
#IBAction func profileNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(ProfileVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
doNotDisturbLabel.isHidden = true
if !userName.isEmpty {
welcomeLabel.text = "Welcome Back, " + userName + "!"
} else {
welcomeLabel.text = ""
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let friendsVC = segue.destination as? FriendsVC else {
return
}
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).getDocument { (snapshot, err) in
if let err = err {
print(err.localizedDescription)
} else {
let data = snapshot!.data()!
let requests = data[Constants.Firestore.Keys.requests] as? [String]
if let requests = requests {
friendsVC.requests = requests
}
}
}
}
class FriendsVC: UIViewController {
//var friends: [Friend] = User.current.friends
var friends: [User] = []
var requests: [String]?
#IBOutlet weak var requestsNumberLabel: UILabel!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendRequestsButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var friendsTitle: UILabel!
#IBOutlet weak var friendTableView: UITableView!
#IBOutlet weak var addFriendButton: UIButton!
#IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
#IBAction func friendRequestsTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toRequests, sender: self)
}
#IBAction func homeNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(HomeVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
friendTableView.backgroundView?.backgroundColor = .white
friendsTitle.isHidden = false
UserService.getUserArray(uids: User.current.friendUids, completion: { (users) in
guard let users = users else {
print("User has no friends")
return
}
self.friends = users
self.friendTableView.reloadData()
})
guard let requests = self.requests else {
friendRequestsButton.isHidden = true
requestsNumberLabel.isHidden = true
self.tableViewTopConstraint.constant = 0
return
}
requestsNumberLabel.text = requests.count.description
// Do any additional setup after loading the view.
friendTableView.delegate = self
friendTableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let homeVC = segue.destination as? HomeVC {
homeVC.userName = User.current.firstName
} else if let requestsVC = segue.destination as? RequestsVC {
UserService.getUserArray(uids: self.requests!) { (requesters) in
if let requesters = requesters {
requestsVC.requesters = requesters
}
}
}
}
}
When my app loads into the home screen, there is no problem, and when a button is tapped to transition to FriendsVC, there is no problem. However, when I try to initiate the transition from HomeVC to ProfileVC or from FriendVC to HomeVC, I get the error: "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" at the self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill lines in my viewDidLoad methods. These segues have something in common in that these are the ones where I override the prepare() function, but I'm not sure what I'm doing wrong
Site used: https://material.io/develop/ios/components/ripple/
Here is my code:
import MaterialComponents.MaterialRipple
class ViewController: UIViewController {
// let rippleView = MDCRippleView()
let rippleTouchController = MDCRippleTouchController()
#IBOutlet weak var playBtn: UIButton!
#IBOutlet weak var levelsBtn: UIButton!
#IBOutlet weak var topicsBtn: UIButton!
#IBOutlet weak var settingsBtn: UIButton!
#IBOutlet weak var instaBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//This works for instabtn (lastone)
// rippleTouchController.rippleView.rippleColor = .lightGray
// rippleTouchController.addRipple(to: playBtn)
// rippleTouchController.addRipple(to: levelsBtn)
// rippleTouchController.addRipple(to: topicsBtn)
// rippleTouchController.addRipple(to: settingsBtn)
// rippleTouchController.addRipple(to: instaBtn)
}
override func viewDidAppear(_ animated: Bool) {
// Currently only works for playbtn
rippleTouchController.rippleView.rippleColor = .lightGray
rippleTouchController.addRipple(to: levelsBtn)
rippleTouchController.addRipple(to: topicsBtn)
rippleTouchController.addRipple(to: settingsBtn)
rippleTouchController.addRipple(to: instaBtn)
rippleTouchController.addRipple(to: playBtn)
}
}
I've tried to put the code in viewDidAppear but it doesn't make a difference. Any thoughts?
Foreach button you have to create a MDCRippleTouchController.
let rippleTouchController = MDCRippleTouchController()
let rippleTouchController2 = MDCRippleTouchController()
let rippleTouchController3 = MDCRippleTouchController()
let rippleTouchController4 = MDCRippleTouchController()
let rippleTouchController5 = MDCRippleTouchController()
override func viewDidAppear(_ animated: Bool) {
rippleTouchController.rippleView.rippleColor = .lightGray
rippleTouchController.addRipple(to: levelsBtn)
rippleTouchController2.addRipple(to: topicsBtn)
rippleTouchController3.addRipple(to: settingsBtn)
rippleTouchController4.addRipple(to: instaBtn)
rippleTouchController5.addRipple(to: playBtn)
}
I'm working right now on my first Swift project. I've got 2 stepper and one label - both stepper are sending their values to it. How can I add the value of the second stepper to the label, in which the value of the first stepper is already? Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
stepper.wraps = true
stepper.autorepeat = true
stepper.maximumValue = 10000
stepper2.wraps = true
stepper2.autorepeat = true
stepper2.maximumValue = 10000
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBAction func stepperValueChanged(sender: UIStepper) {
valueLabel.text = Int(sender.value).description
}
#IBOutlet weak var stepper2: UIStepper!
#IBAction func stepper2ValueChanged(sender: UIStepper) {
valueLabel.text = Int(sender.value).description
}
}
Thank you!
If you want to combine the two values to ONE String and show this String on your Label, than you have to create a new function that does this for you. I added such a function to your code:`
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
stepper.wraps = true
stepper.autorepeat = true
stepper.maximumValue = 10000
stepper2.wraps = true
stepper2.autorepeat = true
stepper2.maximumValue = 10000
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBAction func stepperValueChanged(sender: UIStepper) {
// valueLabel.text = Int(sender.value).description
addValuesToASumAndPutItIntoTheLabel()
}
#IBOutlet weak var stepper2: UIStepper!
#IBAction func stepper2ValueChanged(sender: UIStepper) {
// valueLabel.text = String(sender.value)
addValuesToASumAndPutItIntoTheLabel()
}
func addValuesToASumAndPutItIntoTheLabel() {
let summe : Int = Int(stepper.value + stepper2.value)
valueLabel.text = summe.description
}
}`
i'm making an app that required Logging In. the problem is when i run my app to try it and type wrong user info it proceed to the next view controller without giving the error !. Heres my code i don't whats the problem !
{
#IBOutlet weak var ActivityIndicator: UIActivityIndicatorView!
#IBOutlet weak var Message: UILabel!
#IBOutlet weak var UsernameTextField: UITextField!
#IBOutlet weak var PasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
ActivityIndicator.hidden = true
ActivityIndicator.hidesWhenStopped = true
// Do any additional setup after loading the view.
}
#IBAction func LogInButtonTapped(sender: AnyObject) {
LogIn()
}
func LogIn() {
// Start activity indicator
ActivityIndicator.hidden = false
ActivityIndicator.startAnimating()
// if there is a user
var user = PFUser()
user.username = UsernameTextField.text
user.password = PasswordTextField.text
PFUser.logInWithUsernameInBackground(UsernameTextField.text, password:PasswordTextField.text) {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("LogInToHomeVC", sender: self)}
println("Logged In")
} else {
self.ActivityIndicator.stopAnimating()
if let Message: AnyObject = error!.userInfo!["error"] {
self.Message.text = "\(Message)"}
println("Could Not Find User")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
so the question is how to let the user try again and not let him enter the Home Page?
I want to pass a Bool value from on view controller to another without the help of segues. So i referred & got Delegates.
I have applied delegates in my App. But the Delegate method is not being called. I don't know where i am making the mistake.
So Please help me.
MainViewController
class MainViewController: UIViewController, WriteValueBackDelegate {
#IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
Second View Controller
class LoginController: UIViewController {
#IBOutlet weak var LoginLabel: UILabel!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var pwd: UITextField!
var LoggedInL :Bool?
var mydelegate: WriteValueBackDelegate?
override func viewDidLoad() {
super.viewDidLoad() }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func onSubmit(sender: AnyObject) {
Alamofire.request(.GET, "http://www.jive.com/index.php/capp/user_verification/\(email.text)/\(pwd.text)")
.responseJSON { (_, _, data, _) in
println(data)
let json = JSON(data!)
let name = json["first_name"].stringValue
let status = json["valid_status"].intValue
println(status)
var e = self.email.text
println(e)
self.LoginLabel.text = "Hey \(name)!"
if status == 1{
println("Correect")
self.LoggedInL = true
self.mydelegate?.writeValueBack(true)
}else {
self.LoggedInL = false
println("Error")
}
}
navigationController!.popViewControllerAnimated(true)
}
}
protocol WriteValueBackDelegate {
func writeValueBack(value: Bool)
}
you didn't initialize the delegate, and no need to, delegates are usually for async callbacks. do that instead:
class MainViewController: UIViewController {
static var sharedInstace : MainViewController?;
#IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
MainViewController.sharedInstace = self; //this is better from init function
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
}
in login view controller
MainViewController.sharedInstance?.writeValueBack(true)
In MainViewControlleryou need a reference of the LoginController instance maybe with an IBOutlet and then set the delegate in viewDidLoad
#IBOutlet weak var loginController : LoginController!
override func viewDidLoad() {
super.viewDidLoad()
loginController.mydelegate = self
}