How do I adjust the size of a UITextView? Swift - ios

I have a problem with my app, look at this pic
Now I'm typing on textView , I want a way to resize the textview or move it to top or scrolling to the last where I'm typing please help
I saw many answers here but all not working with me , and this is the code when i tried one of the answers
import UIKit
class AddEditClassNoteViewController: UIViewController {
#IBOutlet var keyboardHeightLayoutConstraint: NSLayoutConstraint?
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.
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
#IBOutlet weak var noteTextBox: UITextView!
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
self.noteTextBox.resignFirstResponder()
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true,moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false,moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
var movementDuration:NSTimeInterval = 0.3
var 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()
}
}
Im using Swift IOS 8

It seems like you're asking for several things, (all of which, I'm guessing, already have answers on Stack Overflow) but I'll do my best to give you a few examples.
First, what you have so far seems to hide the keyboard when you tap on the view. That may be partially defeating your purpose.
Second, if you're trying to scroll to the top of the your noteTextBox, try using:
noteTextBox.setContentOffset(CGPointMake(0, 0), animated: true) [Use animted: true if you want a scrolling animation. You may not, I don't know]
Third, check out this question for resizing the UITextView: Click Here
Fourth, check out this question for returning to a "remembered" position on your UIView: Click Here
Good luck,
Kyle

for any one need the answer with Swift language , The answer is as following simple change only .
import UIKit
class AddEditClassNoteViewController: UIViewController {
var keyboardShowing = false
#IBOutlet weak var noteTextBox: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHide:", name: UIKeyboardWillHideNotification, object: nil)
// Do any additional setup after loading the view.
}
override func shouldAutorotate() -> Bool {
return !self.keyboardShowing
}
// much simpler than in iOS 7; a lot of the touchy bugs are gone in iOS 8
// as long as you play your part (adjust content offset),
// iOS 8 will play its part (scroll cursor to visible)
// and we don't have to animate
func keyboardShow(n:NSNotification) {
self.keyboardShowing = true
let d = n.userInfo!
var r = (d[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
r = self.noteTextBox.convertRect(r, fromView:nil)
self.noteTextBox.contentInset.bottom = r.size.height
self.noteTextBox.scrollIndicatorInsets.bottom = r.size.height
}
func keyboardHide(n:NSNotification) {
self.keyboardShowing = false
self.noteTextBox.contentInset = UIEdgeInsetsZero
self.noteTextBox.scrollIndicatorInsets = UIEdgeInsetsZero
}
func doDone(sender:AnyObject) {
self.view.endEditing(false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
self.noteTextBox.resignFirstResponder()
}
}
Thanks for all who was trying to helping me .

Related

How to rotate a UILabel upside down in XCode, using Swift?

I would like to have a label that is displayed upside down, when the view did load.
Here is the default code given in the ViewController.swift, and I had also added the UILabel as an outlet.
import UIKit
class ViewController: UIViewController {
#IBOutlet var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Also sorry if this is a dumb question I am very new to IOS development and swift.
To rotate your label in viewDidLoad just use the following :
Swift
override func viewDidLoad() {
super.viewDidLoad()
var aLabel: UILabel = ...
aLabel.transform = CGAffineTransformMakeRotation(M_PI)
}
Objective C
-(void) viewDidLoad {
[super viewDidLoad];
UILabel *aLabel = ...
aLabel.transform = CGAffineTransformMakeRotation(M_PI);
}
M_PI will make a rotation of 180 degrees which will result in an upside down label.
Swift 3x, Xcode 8x
override func viewDidLoad() {
super.viewDidLoad()
var aLabel: UILabel = ...
aLabel.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
}
Xcode 8.3.3
override func viewDidLoad() {
super.viewDidLoad()
var aLabel: UILabel = ...
aLabel.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
}

keyboard controlling function error with Xcode 7

I was trying to create a function in order to put keyboard away by clicking outside of the keyboard or return key within the keyboard, but unfortunately it only worked when I clicked outside of the keyboard, it doesn't work to press the return key in the keyboard.
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet var numberEnter: UITextField!
#IBAction func findButton(sender: AnyObject) {
resultLabel.text = numberEnter.text
}
#IBOutlet var resultLabel: UILabel!
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.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField:UITextField) -> Bool{
textField.resignFirstResponder()
return true
}
}
If you haven't set the delegate for your text field you will need to do that. You can set the delegate in Interface Builder or in code. See this StackOverflow answer for an example: Text Field Should Return, is this correct for ios7?

inputAccessoryView not showing above keyboard

Problem relates to this.
I'm trying to use a custom view that I made that has two TextField inputs and a button, I made it using IB its xib, I've placed it in my story board and have it set to be at the bottom of my view.
The problem comes in when I want to make ContactInfoView the keyboards accessory view.
class ViewController: UIViewController, UITextViewDelegate {
#IBOutlet var cameraPreview: UIView!
#IBOutlet weak var ContactInfoView: KeyboardAccessoryView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//cameraPreviewLayer!.frame = cameraPreview.bounds
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillAppear"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide"), name: UIKeyboardWillHideNotification, object: nil)
ContactInfoView.NameInput.inputAccessoryView = ContactInfoView
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
// keyboard stuff
var accessoryView = KeyboardAccessoryView(frame: CGRectZero);
override var inputAccessoryView: KeyboardAccessoryView {
return accessoryView
}
override func becomeFirstResponder() -> Bool {
return true
}
override func canBecomeFirstResponder() -> Bool {
return true
}
func keyboardWillAppear() {
print("Keyboard appeared")
}
func keyboardWillHide() {
print("Keyboard hidden")
}
}
ContactInfoView.NameInput.inputAccessoryView = ContactInfoView isn't placing the view on top of the keyboard.
I fooled out around with the code and it started to crash relating to the link provided, But trying that solution didn't work either.
According to the comment in the UITextView.h file:
#property (nullable, readwrite, strong) UIView *inputView;
#property (nullable, readwrite, strong) UIView *inputAccessoryView;
Presented when object becomes first responder. If set to nil, reverts to following responder chain. If set while first responder, will not take effect until reloadInputViews is called.
You should call reloadInputViews method after setting input.. property.
Yes, This Looks Little Tricky since everything seems fine and same as everyone and the Xcode Auto Suggestion and Completion Tools Helps you to complete the predicted "override" Functions..
Here Is A simple Mistakes that I made While Showing "inputAccessoryView"
I Entered Xcode Suggested Text For Completing "inputAccessoryView" And "inputAccessoryView" for Override Function.
But For Adding "override var inputAccessoryView: UIView?" Func its okay To Select from Xcode Suggestion / Auto Completion
override var inputAccessoryView: UIView? {
get {
return inputContainerView
}
}
For "override var canBecomeFirstResponder : Bool" you should make sure that
you type ": Bool" and not the "() -> Bool", Like I made mistakes couple of time.
So Please If you want You can type yourself or just Copy Below Code Paste in your Class Anywhere and it will work Smoothly.
override var inputAccessoryView: UIView? {
get {
let inputContainerView = UIView()
inputContainerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50)
inputContainerView.backgroundColor = UIColor.gray
let textfield = UITextField()
textfield.text = "asasfdfs df sdf sdf ds f"
textfield.frame = CGRect(x: 0, y: 0, width: inputContainerView.frame.size.width, height: 50)
inputContainerView.addSubview(textfield)
// You can add Any Other Objects Like UIButton, Image, Label //you want And Constraints too.
return inputContainerView
}
}
override var canBecomeFirstResponder : Bool {
return true
}
In the code above, you are assigning the property InputAccessoryView not the property inputAccessoryView. Case is important.
Assuming everything else is setup correctly, this should get it to work, but there is something I don't understand. Why is your text field/text view a property of your input accessory view? If NameInput is a subview of ContactInfoView, then setting ContactInfoView.NameInput.inputAccessoryView will not work.

Swift - 1 screen to another screen

I have set you my UI for both screens and I don't want to do the connect the screens in main.storyboard. I want to click a button and it will take to that screen, I will do the fade animations and stuff like that later. I just need to know how to go to one screen to the next screen when I press a button. I can give an example of what I am talking about down below.
Example: In flappy bird before you start the game it tell you to tap on the screen, then when you tap the text fades out. That is what I want to do with my game. I am not sure if that is another screen or if that is 1 view that makes certain labels disappear once the screen is tapped.
My MainMenuViewController:
import UIKit
import SpriteKit
class MainMenuViewController: UIViewController {
var mainMenuScene: MainMenuScene!
#IBOutlet weak var playButton: UIButton!
#IBAction func playButtonPressed(sender: AnyObject) {
mainMenuScene.playButtonPressed(sender)
}
#IBAction func playerButtonPressed(sender: AnyObject) {
println("player")
}
#IBAction func LeaderboardButtonPressed(sender: AnyObject) {
println("leaderboard")
}
#IBAction func shopButtonPressed(sender: AnyObject) {
println("shop")
}
override func viewDidLoad() {
super.viewDidLoad()
//set up game screens
// Configure the view
// store a ref
// Create and configure the scene
mainMenuScene?.scaleMode = .AspectFill
// Present the scene
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
My MainMenuScene:
import Foundation
import UIKit
import SpriteKit
class MainMenuScene: SKScene {
var movingGround: PPMovingGround!
var square1: PPSquare1!
var wallGen: PPWallGen!
var isStarted = false
var playButton: UIButton!
func playButtonPressed(sender: AnyObject) {
start()
}
func start() {
isStarted = true
square1.stop()
movingGround.start()
wallGen.startGenWallsEvery(1)
}
override func didMoveToView(view: SKView) {
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
}
override func update(currentTime: CFTimeInterval) {
}
}
I want to connect this code to my GameScene File. How do I do it?
I think I know what you're aiming for, since you don't want to do work with the Main.storyboard directly, you could do this:
presentViewController(YourNextViewController, animated: true, completion: nil)
you would call that in the ViewController you are currently in to get to the next one.
Let's say you are on the main screen, as you said in Flappy Bird, when you tap the button, it could change to a different View Controller
My tip would be to nest this method in a function, so you can call it in a gameStart function, like so:
func changeViewControllers() {
presentViewController(GameViewController, animated: true, completion: nil)
}
then call this in your gameStart():
func gameStart() {
changeViewControllers()
//other code
}
//=====================================================================
Alright, I'm going to help you get to another view when you tap your play button, add the following code:
#IBAction func playButtonPressed(sender: AnyObject) {
mainMenuScene.playButtonPressed(sender)
}

Swift-Move view up when keyboard appears with constraints

I am using the following code from "Programming iOS 8". I have a subview with constraints that contains a simple textfield. This view has top and bottom to superview constraints, which I have outlets for. I have an outlet for the subview as well. The goal here is that when the keyboard appears, it pushes this subview up. I get an error on the line "let f = self.fr!.frame" Thread 1: EXC_BAD_INSTRUCTION. Does it have to do with needing to unwrap the optional? Could it be an issue with my constraints? Any help would be much appreciated. Thanks.
import UIKit
class ViewController: UIViewController {
#IBOutlet var topSpace: NSLayoutConstraint!
#IBOutlet var bottomSpace: NSLayoutConstraint!
#IBOutlet var slidingView: UIView!
var fr: UIView?
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardShow:",
name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardHide:",
name: UIKeyboardWillHideNotification, object: nil)
super.viewDidLoad()
}
func textFieldDidBeginEditing(tf: UITextField) {
self.fr = tf // keep track of the first responder
}
func textFieldShouldReturn(tf: UITextField) -> Bool {
tf.resignFirstResponder()
self.fr = nil
return true
}
func keyboardShow(n:NSNotification) {
let d = n.userInfo!
var r = (d[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
r = self.slidingView.convertRect(r, fromView:nil)
let f = self.fr!.frame
let y : CGFloat =
f.maxY + r.size.height - self.slidingView.bounds.height + 5
if r.origin.y < f.maxY {
self.topSpace.constant = -y
self.bottomSpace.constant = y
self.view.layoutIfNeeded()
}
}
func keyboardHide(n:NSNotification){
self.topSpace.constant = 0
self.bottomSpace.constant = 0
self.view.layoutIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If I'm not mistaken, the keyboard shows before you start editing, so your self.fr is still nil when your keyboard is shown. Check to see if it's nil. It shouldn't have to do anything with the optional unwrapping. It only fails when you unwrap a null.

Resources