I use uipageViewController for sliding pages. Each page has own ViewController:ContentViewController. In one of page I have button. When user click on this button it should go to another ViewController (let say home page). When I click on the button it change state, but redirection doesn't work. It seems that smth wrong with pushViewController?
Here is my code ::
class ViewController: UIViewController, UIPageViewControllerDataSource {
var pageViewController : UIPageViewController!
var pageTitles : NSArray!
var pageImages : NSArray!
let controllers = ["FirstViewController","SecondViewController"]
#IBOutlet weak var restartButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.pageTitles = NSArray(objects: "Explore", "Today Widget")
self.pageImages = NSArray(objects: "page1","page2")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController")as! UIPageViewController
self.pageViewController.dataSource = self
var startVC = self.viewControllerAtIndex(0)as ContentViewController
var viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0,40,self.view.frame.width,self.view.frame.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
self.view.backgroundColor = UIColor(red: (25/255.0), green: (127/255.0), blue: (216/255.0), alpha: 1.0)
// 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.
}
#IBAction func restartAction(sender: AnyObject) {
var startVC = self.viewControllerAtIndex(0)as ContentViewController
var viewControllers = NSArray (object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil)
}
func viewControllerAtIndex(index : Int)->ContentViewController
{
if (self.pageTitles.count == 0) || (index >= self.pageTitles.count){
return ContentViewController();
}
var vc:ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController")as! ContentViewController
vc = self.storyboard?.instantiateViewControllerWithIdentifier(controllers[index])as! ContentViewController
vc.pageIndex = index
return vc;
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == 0 || index == NSNotFound){
return nil
}
index--
return self.viewControllerAtIndex(index);
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == NSNotFound){
return nil
}
index++
if (index == self.pageTitles.count){
return nil
}
return self.viewControllerAtIndex(index)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return self.pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
#IBAction func secondViewController(sender: AnyObject) {
let next = self.storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as? ThirdViewController
navigationController?.pushViewController(next!,animated: true)
}
Related
My app retrieves an image from URL, but I need to change the image size before it appears on the user interface in my tableview.
Here is my tableViewController code:
import UIKit
import Firebase
import Alamofire
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postField: MaterialTextField!
#IBOutlet weak var imageSelectorImage: UIImageView!
var posts = [Post]()
var imageSelected = false
var imagePicker: UIImagePickerController!
static var imageCache = NSCache()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
postField.delegate = self
//tableView.estimatedRowHeight = 400
//tableView.rowHeight = UITableViewAutomaticDimension
imagePicker = UIImagePickerController()
imagePicker.delegate = self
DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.Value, withBlock: { snapshot in
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.insert(post, atIndex: 0)
}
}
}
self.tableView.reloadData()
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 167)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 167)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.1
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
print(post.postDescription)
if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
if let url = post.imageUrl {
img = FeedViewController.imageCache.objectForKey(url) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImage.image = image
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func makePost(sender: AnyObject) {
//TODO: Add loading spinner while data is being processed
if let txt = postField.text where txt != "" {
if let img = imageSelectorImage.image where imageSelected == true {
let urlStr = URL_IMGSHACK
let url = NSURL(string: urlStr)!
//FIXME: Add error handling
let imgData = UIImageJPEGRepresentation(img, 0.2)!
let keyData = API_KEY_IMG.dataUsingEncoding(NSUTF8StringEncoding)!
let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!
Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imgData, name: "fileupload", fileName: "image",
mimeType: "image/jpg")
multipartFormData.appendBodyPart(data: keyData, name: "key")
multipartFormData.appendBodyPart(data: keyJSON, name: "format")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject>{
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
self.postToFirebase(imgLink)
}
}
}
})
case .Failure(let error):
print(error)
}
}
} else {
self.postToFirebase(nil)
}
}
}
func postToFirebase(imgUrl: String?) {
var post: Dictionary<String, AnyObject> = [
"timestamp": NSNumber(longLong: currentTimeMillis()),
"description": postField.text!,
"likes": 0
]
if imgUrl != nil {
post["imageUrl"] = imgUrl!
}
let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
firebasePost.setValue(post)
postField.text = ""
imageSelectorImage.image = UIImage(named: "camera")
imageSelected = false
tableView.reloadData()
postField.resignFirstResponder()
}
func currentTimeMillis() ->Int64 {
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble * 1000)
}
}
and here is my custom cell:
class PostCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var showcaseImage: UIImageView!
#IBOutlet weak var descriptionText: UILabel!
#IBOutlet weak var likesLabel: UILabel!
#IBOutlet weak var likeImage: UIImageView!
var post: Post!
var request: Request?
var likeRef: Firebase!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: "likeTapped:")
tap.numberOfTapsRequired = 1
likeImage.addGestureRecognizer(tap)
likeImage.userInteractionEnabled = true
}
override func drawRect(rect: CGRect) {
profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
profileImage.backgroundColor = UIColor.clearColor()
profileImage.layer.borderWidth = 2
profileImage.layer.borderColor = UIColor.whiteColor().CGColor
self.profileImage.clipsToBounds = true
self.showcaseImage.clipsToBounds = true
}
func configureCell(post: Post, img: UIImage?){
self.post = post
likeRef = DataService.ds.REF_USERS_CURRENT.childByAppendingPath("likes").childByAppendingPath(post.postKey)
self.descriptionText.text = post.postDescription
self.likesLabel.text = "\(post.likes)"
if post.imageUrl != nil {
if img != nil {
self.showcaseImage.image = img
} else {
request = Alamofire.request(.GET, post.imageUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
if err == nil {
let img = UIImage(data: data!)!
self.showcaseImage.image = img
FeedViewController.imageCache.setObject(img, forKey: self.post.imageUrl!)
} else {
print(err.debugDescription)
}
})
}
} else {
self.showcaseImage.hidden = true
}
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
//This mean we have not liked this specific post
self.likeImage.image = UIImage(named: "heart-empty")
} else {
self.likeImage.image = UIImage(named: "heart-full")
}
})
}
func likeTapped(sender: UITapGestureRecognizer) {
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
self.likeImage.image = UIImage(named: "heart-full")
self.post.adjustLikes(true)
self.likeRef.setValue(true)
} else {
self.likeImage.image = UIImage(named: "heart-empty")
self.post.adjustLikes(false)
self.likeRef.removeValue()
}
})
}
}
Here is an example showing what I want to achieve:
this when user post the portrait image
this when user post the landscape image
In summary, I want the image width to fit the width of the device screen, and the height of the uiimage to be dynamic, regardless of the image orientation (landscape or portrait).
Try this part, where 300x600 is needed size of your image to save.
let image = UIImage(data: data!)
UIGraphicsBeginImageContext(CGSizeMake(300, 600))
image?.drawInRect(CGRectMake(0, 0, 300, 600))
let smallImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
My app retrieves image from URL, but I need to change the image size before it appears on the user interface in my tableview.
this is my code in my tableViewController:
import UIKit
import Firebase
import Alamofire
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postField: MaterialTextField!
#IBOutlet weak var imageSelectorImage: UIImageView!
var posts = [Post]()
var imageSelected = false
var imagePicker: UIImagePickerController!
static var imageCache = NSCache()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
postField.delegate = self
//tableView.estimatedRowHeight = 400
//tableView.rowHeight = UITableViewAutomaticDimension
imagePicker = UIImagePickerController()
imagePicker.delegate = self
DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.Value, withBlock: { snapshot in
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.insert(post, atIndex: 0)
}
}
}
self.tableView.reloadData()
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 167)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 167)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.1
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
print(post.postDescription)
if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
if let url = post.imageUrl {
img = FeedViewController.imageCache.objectForKey(url) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImage.image = image
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func makePost(sender: AnyObject) {
//TODO: Add loading spinner while data is being processed
if let txt = postField.text where txt != "" {
if let img = imageSelectorImage.image where imageSelected == true {
let urlStr = URL_IMGSHACK
let url = NSURL(string: urlStr)!
//FIXME: Add error handling
let imgData = UIImageJPEGRepresentation(img, 0.2)!
let keyData = API_KEY_IMG.dataUsingEncoding(NSUTF8StringEncoding)!
let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!
Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imgData, name: "fileupload", fileName: "image",
mimeType: "image/jpg")
multipartFormData.appendBodyPart(data: keyData, name: "key")
multipartFormData.appendBodyPart(data: keyJSON, name: "format")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject>{
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
self.postToFirebase(imgLink)
}
}
}
})
case .Failure(let error):
print(error)
}
}
} else {
self.postToFirebase(nil)
}
}
}
func postToFirebase(imgUrl: String?) {
var post: Dictionary<String, AnyObject> = [
"timestamp": NSNumber(longLong: currentTimeMillis()),
"description": postField.text!,
"likes": 0
]
if imgUrl != nil {
post["imageUrl"] = imgUrl!
}
let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
firebasePost.setValue(post)
postField.text = ""
imageSelectorImage.image = UIImage(named: "camera")
imageSelected = false
tableView.reloadData()
postField.resignFirstResponder()
}
func currentTimeMillis() ->Int64 {
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble * 1000)
}
}
and here my custom cell:
class PostCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var showcaseImage: UIImageView!
#IBOutlet weak var descriptionText: UILabel!
#IBOutlet weak var likesLabel: UILabel!
#IBOutlet weak var likeImage: UIImageView!
var post: Post!
var request: Request?
var likeRef: Firebase!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: "likeTapped:")
tap.numberOfTapsRequired = 1
likeImage.addGestureRecognizer(tap)
likeImage.userInteractionEnabled = true
}
override func drawRect(rect: CGRect) {
profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
profileImage.backgroundColor = UIColor.clearColor()
profileImage.layer.borderWidth = 2
profileImage.layer.borderColor = UIColor.whiteColor().CGColor
self.profileImage.clipsToBounds = true
self.showcaseImage.clipsToBounds = true
}
func configureCell(post: Post, img: UIImage?){
self.post = post
likeRef = DataService.ds.REF_USERS_CURRENT.childByAppendingPath("likes").childByAppendingPath(post.postKey)
self.descriptionText.text = post.postDescription
self.likesLabel.text = "\(post.likes)"
if post.imageUrl != nil {
if img != nil {
self.showcaseImage.image = img
} else {
request = Alamofire.request(.GET, post.imageUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
if err == nil {
let img = UIImage(data: data!)!
self.showcaseImage.image = img
FeedViewController.imageCache.setObject(img, forKey: self.post.imageUrl!)
} else {
print(err.debugDescription)
}
})
}
} else {
self.showcaseImage.hidden = true
}
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
//This mean we have not liked this specific post
self.likeImage.image = UIImage(named: "heart-empty")
} else {
self.likeImage.image = UIImage(named: "heart-full")
}
})
}
func likeTapped(sender: UITapGestureRecognizer) {
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
self.likeImage.image = UIImage(named: "heart-full")
self.post.adjustLikes(true)
self.likeRef.setValue(true)
} else {
self.likeImage.image = UIImage(named: "heart-empty")
self.post.adjustLikes(false)
self.likeRef.removeValue()
}
})
}
}
this example for what i want to achieve:
this when user post the portrait image
this when user post the landscape image
The point is that I want my image width to always fit the width of device screen, and the height of the uiimage will be dynamic.
so when user post any image with any orientation ( landscape or portrait ), the image will fit the width of the screen, the height will be dynamic.
please help me give the detail where to put your method since i am a newbie about this, how to achieve what i want... im so desperated, is already 1 month and im so stuck about this...
You need to add imageview to storyboard from interface builder in Xcode,then you can set its constraints to fit size of the screen,& also add height constraints which you can change later when you retrieve image from url
I have a problem with my collection view, which gives me a 'blink' a second after the view gets appeared on the screen.
Could it be the viewDidLoad or the viewDidAppear that causes this?
This is my current Swift code:
class HomeViewController: UIViewController
{
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var currentUserProfileImageButton: UIButton!
#IBOutlet weak var currentUserFullNameButton: UIButton!
// MARK: - UICollectionViewDataSource
private var interests = [Interest]()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() == nil {
// the user hasn't logged in yet
showLogin()
} else {
// the user logged in, do something else
fetchInterests()
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
center.addObserverForName("NewInterestCreated", object: nil, queue: queue, usingBlock: { (notification) -> Void in
if let newInterest = notification.userInfo?["newInterestObject"] as? Interest {
if !self.interestWasDisplayed(newInterest) {
self.interests.insert(newInterest, atIndex: 0)
self.collectionView.reloadData()
}
}
})
}
}
func interestWasDisplayed(newInterest: Interest) -> Bool {
for interest in interests {
if interest.objectId! == newInterest.objectId! {
return true
}
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UIScreen.mainScreen().bounds.size.height == 480.0 {
let flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.itemSize = CGSizeMake(250.0, 300.0)
}
configureUserProfile()
}
func configureUserProfile()
{
// configure image button
currentUserProfileImageButton.contentMode = UIViewContentMode.ScaleAspectFill
currentUserProfileImageButton.layer.cornerRadius = currentUserProfileImageButton.bounds.width / 2
currentUserProfileImageButton.layer.masksToBounds = true
}
private struct Storyboard {
static let CellIdentifier = "Interest Cell"
}
#IBAction func userProfileButtonClicked()
{
PFUser.logOut()
showLogin()
}
// MARK: - Fetch Data From Parse
func fetchInterests()
{
let currentUser = User.currentUser()!
let interestIds = currentUser.interestIds
if interestIds?.count > 0
{
let interestQuery = PFQuery(className: Interest.parseClassName())
interestQuery.orderByDescending("updatedAt")
interestQuery.cachePolicy = PFCachePolicy.NetworkElseCache
interestQuery.whereKey("objectId", containedIn: interestIds)
interestQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let interestObjects = objects as [PFObject]? {
self.interests.removeAll()
for interestObject in interestObjects {
let interest = interestObject as! Interest
self.interests.append(interest)
}
self.collectionView.reloadData()
}
} else {
print("\(error!.localizedDescription)")
}
})
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Show Interest" {
let cell = sender as! InterestCollectionViewCell
let interest = cell.interest
let navigationViewController = segue.destinationViewController as! UINavigationController
let interestViewController = navigationViewController.topViewController as! InterestViewController
interestViewController.interest = interest
} else if segue.identifier == "CreateNewInterest" {
_ = segue.destinationViewController as! NewInterestViewController
} else if segue.identifier == "Show Discover" {
_ = segue.destinationViewController as! DiscoverViewController
}
}
func showLogin()
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let welcomeNavigationVC = storyboard.instantiateViewControllerWithIdentifier("WelcomeNavigationViewController") as! UINavigationController
self.presentViewController(welcomeNavigationVC, animated: true, completion: nil)
}
}
extension HomeViewController : UICollectionViewDataSource{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return interests.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath: indexPath) as! InterestCollectionViewCell
cell.interest = self.interests[indexPath.item]
return cell
}
}
extension HomeViewController : UIScrollViewDelegate{
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.memory
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.memory = offset
}
}
extension HomeViewController : PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate{
func presentLoginViewController()
{
let logInController = PFLogInViewController()
let signupController = PFSignUpViewController()
signupController.delegate = self
logInController.delegate = self
logInController.fields = [PFLogInFields.UsernameAndPassword, PFLogInFields.LogInButton, PFLogInFields.SignUpButton]
logInController.signUpController = signupController
presentViewController(logInController, animated: true, completion: nil)
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser)
{
logInController.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser)
{
signUpController.dismissViewControllerAnimated(true, completion: nil)
}
}
Thanks guys :)
I have just a camera on my CameraController. I want the picture from my CameraContoller to go to my ComposeViewController inside of the image View in the ComposeViewController. so basically I need it so the the picture taken transfers to the other view controller once taken. There are 2 separate view controllers below in the code.
Code:
import UIKit
import AVFoundation
class CameraController : UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
#IBOutlet var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error : NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
if (error == nil && captureSession?.canAddInput(input) != nil){
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil){
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer)
captureSession?.startRunning()
}
}
}
#IBOutlet var tempImageView: UIImageView!
func didPressTakePhoto(){
if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
(sampleBuffer, error) in
if sampleBuffer != nil {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
var dataProvider = CGDataProviderCreateWithCFData(imageData)
var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)
var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)
self.tempImageView.image = image
self.tempImageView.hidden = false
}
})
}
}
var didTakePhoto = Bool()
func didPressTakeAnother(){
if didTakePhoto == true{
tempImageView.hidden = true
didTakePhoto = false
}
else{
captureSession?.startRunning()
didTakePhoto = true
didPressTakePhoto()
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
didPressTakeAnother()
}
}
//-----Below is my Next View Controller where i want the image from the above view controller to show up--------------------------------------- --------------------------------------------------------------------------- --------------
class ComposeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
let tap = UITapGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "GotoProfile")
swipe.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipe)
tap.numberOfTapsRequired = 2
tap.addTarget(self, action: "GoBack")
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func CaptonField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if range.length + range.location > count(captionTextView.text){
return false
}
let NewLength = count(captionTextView.text) + count(string) - range.length
return NewLength <= 35
}
#IBAction func chooseImageFromCamera() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker,animated: true, completion:nil)
}
func GotoProfile(){
self.performSegueWithIdentifier("NewCameraViewFromComposeSegue", sender: nil)
}
func GoBack(){
self.performSegueWithIdentifier("GoBackFromCamerasegue", sender: nil)
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded)
let file: PFFile = PFFile(data: imageData)
let fileCaption: String = self.captionTextView.text
var photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["date"] = localDate
photoToUpload.save()
println("Successfully Posted.")
let vc: AnyObject? = self.storyboard?.instantiateViewControllerWithIdentifier("NavigationController")
self.presentViewController(vc as! UIViewController, animated: true, completion: nil)
}
}
Are you using a segue to get from the first to the second ViewController ?
If so you can access the second VC in in your first VC in the prepareForSegue function :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ComposeVCIdentifier" {
let composeViewController = segue.destinationViewController as! ComposeViewController
composeViewController.someVariable = myPicture
}
}
I am creating a page view application. I have written code for the ViewController:
import UIKit
class ViewController: UIViewController {
var pageViewController : UIPageViewController!
var pageTitles : NSArray!
var pageImages : NSArray!
#IBAction func restartAction(sender: AnyObject) {}
override func viewDidLoad() {
super.viewDidLoad()
self.pageTitles = NSArray(objects: "This Is Page One!", "This Is Page Two!")
self.pageImages = NSArray(objects: "page1", "page2")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self // <–– Error
let startVC = self.viewControllerAtIndex(0) as ContentViewController
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewControllerAtIndex(index: Int) -> ContentViewController {
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return ContentViewController()
}
let vc : ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
func pageViewController(pageViewController: UIPageViewController, viewcontrollerBeforeViewController viewController: UIViewController) ->UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if index == 0 || index == NSNotFound {
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewcontrollerAfterViewController viewController: UIViewController) ->UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if index == NSNotFound {
return nil
}
index++
if index == self.pageTitles.count {
return nil
}
return self.viewControllerAtIndex(index)
}
}
But I am getting an error on this line self.pageViewController.dataSource = self. The error is:
Cannot assign to property: 'self' is immutable
I am unsure of why self is immutable and how to fix it. If someone could please help, thanks in advance.
In swift you'll need to call self.pageViewController.setDelegate(self)
Delegates have been declared as methods, not properties in some cases
I think the compiler is not being very helpful here - try declaring the controller as following datasource protocol and see if that fixes this odd error
class ViewController: UIViewController, UIPageViewControllerDataSource { etc