Edit:
I was able to change the code in a way, that the program does not crash anymore. However, there is just one tiny problem left for the code to work:
As you can see in my console output, the coordinates for origin2 are not the same as in origin 1.
origin1: (268.0, 241.0) origin2: (116.0, 323.0) sender view center:
Optional((146.5, 397.0))
So I need to get the imageOrigin1-values from viewDidLoad() and use them im func handlePan(sender:UIPanGestureRecognizer).
I just don't know how to do this...
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
#IBOutlet weak var correctField: UIImageView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
let imageOrigin1 = image.frame.origin
print("origin1: \(imageOrigin1)")
}
#IBAction func handlePan(sender:UIPanGestureRecognizer) {
let imageOrigin2 = image.frame.origin
let translation = sender.translationInView(self.view)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
if sender.state == UIGestureRecognizerState.Ended {
if correctField.frame.contains(sender.view!.center){
print("Correct")
sender.setTranslation(CGPointZero, inView: self.view)
} else{
print("origin2: \(imageOrigin2)")
print("sender view center: \(sender.view?.center)")
//sender.view?.center = imageOrigin
}
}
}
}
I solved this problem myself, adding a new class and passing the variables via set and get methods:
CLASS:
import UIKit
class Origin {
var positionOrigin: CGPoint!
func setImageOrigin(Image: UIImageView) {
positionOrigin = Image.center
}
func getImageOrigin() -> CGPoint {
return positionOrigin
}
}
VIEW CONTROLLER:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var correctField: UIImageView!
#IBOutlet weak var image: UIImageView!
var imageOrigin = Origin()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
imageOrigin.setImageOrigin(image)
}
#IBAction func handlePan(sender:UIPanGestureRecognizer) {
let translation = sender.translationInView(self.view)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
sender.setTranslation(CGPointZero, inView: self.view)
}
if sender.state == UIGestureRecognizerState.Ended {
if correctField.frame.contains(sender.view!.center){
print("Correct")
} else{
image.center = imageOrigin.getImageOrigin()
}
}
}
}
Related
How to create array of multiple mp4 or mov files in swift. I was able to display the single video in uiwebview. I have pagecontrol to display some text but I need to display different videos same like texts. When the page control starts it should display next video. Here is the code for first view controller and page view controller.
import UIKit
class ViewController: UIViewController,UIPageViewControllerDataSource {
//var pageImages:NSArray!
var ouotes: NSArray!
var video: NSArray!
var pageViewController:UIPageViewController!
#IBOutlet weak var GenerateNumbers: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
video = ["2.mov", "1.mov", "4.mov"]
ouotes = ["sometext" ]
// NSArray(objects:"ap", "bg", "gfb")
/* UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "money")?.draw(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)*/
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyPageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let initialContenViewController = self.pageTutorialAtIndex(0) as ContentHolder
self.pageViewController.setViewControllers([initialContenViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: self.view.frame.size.height-100)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMove(toParentViewController: self)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pageTutorialAtIndex(_ index: Int) -> ContentHolder {
let pageContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "ContentHolder") as! ContentHolder
pageContentViewController.imageFileName = ouotes[index] as! String
pageContentViewController.videoFileName = video [index] as! String
pageContentViewController.pageIndex = index
return pageContentViewController
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
{
let viewController = viewController as! ContentHolder
var index = viewController.pageIndex as Int
if (index == 0 || index == NSNotFound) {
return nil
}
index -= 1
return self.pageTutorialAtIndex(index)
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
{
let viewController = viewController as! ContentHolder
var index = viewController.pageIndex as Int
if ((index == NSNotFound)) {
return nil
}
index += 1
if (index == ouotes.count) {
return nil
}
if (index == video.count) {
return nil
}
return self.pageTutorialAtIndex(index)
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
return ouotes.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int{
return 0
}
}
And for the pagecontrol view where texts and videos should be displayed
import Foundation
import UIKit
import AVKit
import AVFoundation
class ContentHolder: UIViewController {
var imageFileName: String!
var videoFileName: String!
var pageIndex:Int!
#IBOutlet weak var EuroScrollView: UIScrollView!
#IBOutlet weak var VideoView: UIWebView!
#IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// let fileURL = NSURL (fileURLWithPath: "/Users/nafu/Desktop/2.mov")
VideoView.loadHTMLString("<iframe width = \"\(self.VideoView.frame.width) \" height =\"\(self.VideoView.frame.height)\" src = \"\(videoFileName)\"> </iframe>", baseURL: nil)
myLabel.text = imageFileName
myLabel.numberOfLines = 0
myLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
myLabel.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks in advance.
I'm very new to Swift, and I'm having trouble using delegates. When the user taps on a table row in AdminAddCatTableViewController, I want to drop a pin on the map at the user's current location in AdminViewController, and I'm trying to do this using a delegate. Obviously there's something wrong with my code, as the pin does not get dropped.
In AdminAddCatTableViewController, I have
import UIKit
import Firebase
protocol AddCatDelegate: class {
func addPin(sender: AdminAddCatTableViewController)
}
class AdminAddCatTableViewController: UITableViewController {
weak var delegate:AddCatDelegate?
let admin = "secret-number"
let ref = Firebase(url: "firease_url")
#IBOutlet weak var snowballGPSLabel: UILabel!
#IBOutlet weak var smokeyGPSLabel: UILabel!
#IBOutlet weak var shadowGPSLabel: UILabel!
#IBOutlet weak var spotsGPSLabel: UILabel!
#IBOutlet weak var sunnyGPSLabel: UILabel!
var catRefArray: [AnyObject] = []
var coord:String = ""
let shareData = ShareData.sharedInstance
func updateCoord() {
if let bar = self.shareData.someString {
self.coord = bar
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "updateCoord", userInfo: nil, repeats: true)
var catNameArray: [AnyObject] = []
catNameArray.append("Snowball")
catNameArray.append("Smokey")
catNameArray.append("Shadow")
catNameArray.append("Spots")
catNameArray.append("Sunny")
for i in 0...4 {
catRefArray.append(self.ref.childByAppendingPath("admin").childByAppendingPath(self.admin).childByAppendingPath(catNameArray[i] as! String))
}
catRefArray[0].observeEventType(.Value, withBlock: { snapshot in
if let value:String = snapshot.value as? String {
self.snowballGPSLabel.text = value
}
}, withCancelBlock: { error in
print(error.description)
// same for the other rows
})
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0) {
let ref0 = self.ref.childByAppendingPath("admin").childByAppendingPath(self.admin)
ref0.updateChildValues(["Snowball": self.coord])
delegate?.addPin(self)
}
// same for other rows
}
In AdminViewController, I have
import UIKit
import MapKit
import CoreLocation
class AdminViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBAction func logOutDidTouch(sender: AnyObject) {
performSegueWithIdentifier("adminToLogin", sender: self)
}
#IBOutlet weak var mapView: MKMapView!
var locationManager: CLLocationManager!
var previousLocation : CLLocation!
var latitude = 0.0;
var longitude = 0.0;
//Declare Class Variable
let shareData = ShareData.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
//On loading the screen the map kit view is shown and the current location is found and is being updated.
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
let status = CLLocationManager.authorizationStatus()
if status == .NotDetermined || status == .Denied || status == .AuthorizedWhenInUse {
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
mapView.delegate = self
mapView.showsUserLocation = true
mapView.mapType = MKMapType(rawValue: 0)!
mapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
mapView.mapType = MKMapType(rawValue: 0)!
}
override func viewWillAppear(animated: Bool) {
//updates the location
locationManager.startUpdatingHeading()
locationManager.startUpdatingLocation()
}
override func viewWillDisappear(animated: Bool) {
locationManager.stopUpdatingHeading()
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
self.latitude = newLocation.coordinate.latitude
self.longitude = newLocation.coordinate.longitude
self.shareData.someString = "\(self.latitude)" + "," + "\(self.longitude)"
print(self.shareData.someString)
}
}
extension AdminViewController: AddCatDelegate {
func addPin(sender:AdminAddCatTableViewController) {
// drop a pin
self.mapView.delegate = self
let coordinate = mapView.userLocation.coordinate
let dropPin = MKPointAnnotation()
dropPin.coordinate = coordinate
dropPin.title = "Cat"
mapView.addAnnotation(dropPin)
}
}
Well you are never setting the delegate on your AdminAddCatTableViewController, so it is always nil and never called.
Why do you even have an extension of AdminViewController? Just remove the extension and make AdminViewController implement the delegate. To set the delegate implement something like this in your AdminViewController:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
if segue.identifier == "YourSegueIdentifier" {
if let vc = segue.destinationViewController as? AdminAddCatTableViewController {
vc.delegate = self
}
}
}
import UIKit
import Alamofire
import SystemConfiguration
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var simpleLabel: UILabel!
#IBOutlet weak var uiNameSearch: UITextField!
#IBOutlet weak var uiGivenName: UITextField!
var patient1 = Patient!()
override func viewDidLoad() {
super.viewDidLoad()
uiNameSearch.delegate = self
uiGivenName.delegate = self
print("ViewController viewDidLoad")
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.simpleLabel.center.x -= self.view.bounds.width
self.uiGivenName.center.x -= self.view.bounds.width
print("Call viewWillAppear")
}
override func viewDidAppear(animated: Bool){
super.viewDidAppear(animated)
UIView.animateWithDuration(0.9 , animations: {
// self.simpleLabel.center.x += self.view.bounds.width
self.uiGivenName.center.x += self.view.bounds.width
})
UIView.animateWithDuration(0.7 , delay: 0.7, options: [], animations: {
self.uiNameSearch.center.x += self.view.bounds.width
}, completion: nil )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func searchForName(sender: UIButton) {
let header = ["Accept" : "application/json"]
let name = uiNameSearch.text!
let given = uiGivenName.text!
if name.characters.count == 0 {
self.view.makeToast( message: "Please insert the family name of the patient!")
} else if given.characters.count == 0 {
self.view.makeToast(message: "Please insert the patient given name!")
} else if checkInternetConnection() == false {
self.view.makeToast(message: "Please connect to the internet!")
} else {
Alamofire.request(.GET, "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Patient?family=\(name)&given=\(given)", headers: header).responseJSON { response in
self.patient1 = Patient(response: response.result.value!)
self.performSegueWithIdentifier("showSegue", sender: sender)
}
}
}
func checkInternetConnection() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
switch textField {
case uiNameSearch:
uiNameSearch.resignFirstResponder()
uiGivenName.becomeFirstResponder()
case uiGivenName:
uiGivenName.resignFirstResponder()
default:
print("")
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender:AnyObject?){
if segue.identifier == "showSegue" {
if let displayViewController = segue.destinationViewController as? DisplayViewController {
displayViewController.patient1 = patient1
}
}
}
}
I want to make uiGivenName and simpleLabel to disappear until the view is created and after when the viewDidAppear is invoked to appear from the left side.
Your view doesn't disappear because you are changing position of views in viewWillAppear and when viewWillAppear gets called, view is about to be added to view hierarchy(i.e view is still not added to view hierarchy.), so its not reflecting in your UI.
So you can do your stuff in viewDidLayoutSubviews because this is the best place if you want to modify your UI just before it actually appears in the screen.
Edit -
Replace this -
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.simpleLabel.center.x -= self.view.bounds.width
self.uiGivenName.center.x -= self.view.bounds.width
print("Call viewWillAppear")
}
with
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.simpleLabel.center.x -= self.view.bounds.width
self.uiGivenName.center.x -= self.view.bounds.width
}
I can't figure out why am I keep getting this Thread:
Error message when running this program.
I'm new to programming and trying an exercise and keep getting this error message.
Also I was trying to figure out how to resize the pictures to fit on the screen.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var memberChoice: UISegmentedControl!
#IBOutlet weak var webView: UIWebView!
#IBAction func getMember(sender:AnyObject){
var member: String =
memberChoice.titleForSegmentAtIndex(memberChoice.selectedSegmentIndex)!
var imageURLString: String!
if member == "Daddy" {
imageURLString = "file: ///Users/natashamays/Desktop/Daddy.jpg"
}
else if member == "Tasha" {
imageURLString = "https://lh3.googleusercontent.com/-2c_GDVdcAFk/UBR7auHIHrI/AAAAAAAAEW8/gJ3F-MVUpL4/w140-h139-p/3.jpg"
}
else if member == "Jasmin" {
imageURLString = "file:///Users/natashamays/Desktop/IMG_3879.JPG"
}
var imageURL: NSURL = NSURL(string:imageURLString)!
webView.loadRequest(NSURLRequest(URL: imageURL))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
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()
}
}