UITextView Font Size - ios

I have a blank/empty UITextView that will output a result based on user-inputs. Everything works great with one small detail that's been bugging me - the font size when it delivers the output is too small for my liking! I tried changing it in the "Attributes Inspector" of storyboard but that only affects it if I decide to have text in the box prior to an output.
My code thus far is
class FreePointViewController: UIViewController {
#IBOutlet weak var fpCoilSizeInput: UITextField!
#IBOutlet weak var fpCoilThicknessInput: UITextField!
#IBOutlet weak var fpLengthInput: UITextField!
#IBOutlet weak var fpPullForceInput: UITextField!
#IBOutlet weak var freePointResult: UITextView!
#IBAction func freePointButton(sender: AnyObject) {
var freePointConst:Double = 20684
calcFreePoint.freePointCoilSize = Double((fpCoilSizeInput.text as NSString).doubleValue)
calcFreePoint.freePointCoilThickness = Double((fpCoilThicknessInput.text as NSString).doubleValue)
calcFreePoint.freePointStretchPipe = Double((fpLengthInput.text as NSString).doubleValue)
calcFreePoint.freePointPullForce = Double((fpPullForceInput.text as NSString).doubleValue)
var freePointArea:Double = M_PI * (calcFreePoint.freePointCoilSize - calcFreePoint.freePointCoilThickness) * calcFreePoint.freePointCoilThickness
var freePoint = (freePointConst * calcFreePoint.freePointStretchPipe * freePointArea) / calcFreePoint.freePointPullForce
var freePointFormat = "0.2"
freePointResult.text = "The pipe is stuck at \(freePoint.format(freePointFormat)) meters"
}
I've tried adding code like [textView setFont:[UIFont boldSystemFontOfSize:15]]; just above my freePointResult.text = ... line but to no avail.

I found the answer to my own question...Check if "Selectable" is checked in the xib/Storyboard attribute inspector. If it's not selectable, the size wont be changed

Related

Looking to accept user input, and calculate a running total - Swift 5/Xcode

I am a beginner working on an app that will function like a golf scorecard. My first issue has come while attempting to accept user input in a (prototype) series of 9 textFields so the user can type in their scores, and then a textView at the end that is not editable that will show the total for the 9 holes. I am trying to get this to be a running total that updates constantly.
I tried passing the inputs from each textField into an array, and returning the sum of the array to a the textView, but still had issues with the data type from the textField being a string, where as I will only be dealing with integers.
My clunky first pass is as follows -
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var holeOneScore: UITextField!
#IBOutlet weak var holeTwoScore: UITextField!
#IBOutlet weak var holeThreeScore: UITextField!
#IBOutlet weak var holeFourScore: UITextField!
#IBOutlet weak var holeFiveScore: UITextField!
#IBOutlet weak var holeSixScore: UITextField!
#IBOutlet weak var holeSevenScore: UITextField!
#IBOutlet weak var holeEightScore: UITextField!
#IBOutlet weak var holeNineScore: UITextField!
#IBOutlet weak var totalForFrontNine: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: Calculate Scores
#IBAction func calculate(_ sender: Any) {
let hole1:Int = Int(holeOneScore.text!)!
let hole2:Int = Int(holeTwoScore.text!)!
let hole3:Int = Int(holeThreeScore.text!)!
let hole4:Int = Int(holeFourScore.text!)!
let hole5:Int = Int(holeFiveScore.text!)!
let hole6:Int = Int(holeSixScore.text!)!
let hole7:Int = Int(holeSevenScore.text!)!
let hole8:Int = Int(holeEightScore.text!)!
let hole9:Int = Int(holeNineScore.text!)!
let totalArray = [hole1, hole2, hole3, hole4, hole5, hole6, hole7, hole8, hole9]
let totalScore = totalArray.reduce(0, +)
totalForFrontNine.text = String(totalScore)
print(totalForFrontNine!)
}
It worked, but barely. Any thoughts to modify this or a complete refresh is fine! I am not tied to anything as i am using this project to just teach me the basics.
Thanks in advance, cheers - glassGarrett
Like #jawadali mentioned, use IBOutletCollection. Here is a tutorial about how to use it.
As for the other issue,
...the data type from the textField being a string, where as I will only be dealing with integers.
A quick solution is to set the keyboardType of your textfield to UIKeyboardTypeNumberPad, or .numberPad in Swift.
textField.keyboardType = .numberPad
Or in storyboard,

Changing font size by using UISlider

I can't get this to work, and this code is not inside viewDidLoad()
#IBOutlet weak var label: UILabel!
#IBOutlet weak var slider: UISlider!
#IBAction func slider(sender: UISlider) {
let senderValue = CGFloat(sender.value)
label?.font = UIFont(name: (label?.font.fontName)!, size:senderValue * 20)
label?.sizeToFit()
}
If you could help in any way that would be great.
The code does not have to be inside viewDidLoad.
Do you use autoLayout to position your view?
This should work:
#IBOutlet weak var label: UILabel!
#IBOutlet weak var slider: UISlider!
#IBAction func sliderAction(sender: AnyObject) {
print("Slider value \(slider.value)")
self.label.font = UIFont.systemFontOfSize(CGFloat(slider.value * 20.0))
}
Check if:
UIFont object is initialised correctly.
Remove label?.sizeToFit. Normally, the label text is drawn with the font you specify in the font property.
Constraints are correctly set on the UILabel object.

Unable to display text from a double to a string

I'm having an issue with a simple app for iOS 9.
When I press the calculate button, the app closes and it will not change the text of the label.
What did I do wrong?
class ViewController: UIViewController {
#IBOutlet weak var weightTextField: UITextField!
#IBOutlet weak var repsTextField: UITextField!
#IBOutlet weak var resultsLabel: UILabel!
#IBAction func calculateButton(sender: AnyObject) {
let numberOfReps = Double(repsTextField.text!)!
let weight = Double(weightTextField.text!)!
let x = (numberOfReps * 0.033)
let x1 = (x + 1)
let max = (weight * x1)
let oneMaxRepString = Double(max)
resultsLabel.text = String(oneMaxRepString)
}
}
#rogue-studios is right. You didn't connect IBOutlets correctly.
I assume that your code would work. Your app could be crashing because your connection between labels/buttons are not connected correctly. Go and make sure that your #IBOutlets are connected to the storyboard objects.
If this does not work, comment the error that you are getting in the console.

Understanding where auto constraints are being set

In the below autolayout challenge 6, from Ray W, I can't understand where in the code, the width and height change after it is tapped more than once.
It is set to 50 in IB, and on the first run through within the tappedImage method, in the last else condition, width.constant = 100, but when does this ever get redefined back to 50 (width.constant = 50)?!?
AND, after the first tap (i.e., width and height of this image = 100), tapping another image next, the width and height of the first image goes back to 50 while the second image grows to 100. Where in the last else condition does it tell the first image to resize to 50?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var rayWidth: NSLayoutConstraint!
#IBOutlet weak var rayHeight: NSLayoutConstraint!
#IBOutlet weak var ray: UIImageView!
#IBOutlet weak var vickiWidth: NSLayoutConstraint!
#IBOutlet weak var vickiHeight: NSLayoutConstraint!
#IBOutlet weak var vicki: UIImageView!
#IBOutlet weak var gregWidth: NSLayoutConstraint!
#IBOutlet weak var gregHeight: NSLayoutConstraint!
#IBOutlet weak var greg: UIImageView!
#IBOutlet weak var micWidth: NSLayoutConstraint!
#IBOutlet weak var micHeight: NSLayoutConstraint!
#IBOutlet weak var mic: UIImageView!
#IBOutlet weak var christineWidth: NSLayoutConstraint!
#IBOutlet weak var christineHeight: NSLayoutConstraint!
#IBOutlet weak var christine: UIImageView!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var bio: UITextView!
var heights:[NSLayoutConstraint]!
var widths:[NSLayoutConstraint]!
var bios: [String]!
var names: [String]!
#IBOutlet weak var emailButton: UIButton!
var previousHeight: NSLayoutConstraint?
var previousWidth: NSLayoutConstraint?
override func viewWillAppear(animated: Bool) {
bios = ["Ray is an indie software developer currently focusing on iPhone and iPad development, and the administrator of this site. He’s the founder of a small iPhone development studio called Razeware, and is passionate both about making apps and teaching others the techniques to make them.", "Vicki Wenderlich discovered a love of digital art in 2009, and has been making app art and digital illustrations ever since. She is passionate about helping people pursue their dreams, and makes free app art for developers available on her website, http://www.vickiwenderlich.com.", "Greg is an iOS developer and trainer, and has been on the raywenderlich.com editorial team since 2012. He has been nerding out with computers since the Commodore 64 era in the 80s and continues to this day on the web and on iOS. He likes caffeine, codes with two-space tabs, and writes with semicolons.", "Mic Pringle is a developer, editor, podcaster, and video tutorial maker. He's also Razeware's third full-time employee. When not knee-deep in Swift or stood in-front of his green screen, he enjoys spending time with his wife Lucy and their daughter Evie, as-well as attending the football matches of his beloved Fulham FC. You can find Mic on Twitter, GitHub, and Stack Overflow.", "Christine is Ray's administrative assistant. She tries to keep order in the ever expanding world of raywenderlich.com so that Ray and the team can stay focused on making more tutorials, books, and apps!"]
names = ["Ray Wenderlich", "Vicki Wenderlich", "Greg Heo", "Mic Pringle", "Christine Sweigart"]
name.text = ""
emailButton.hidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
var razeware = [ray, vicki, greg, mic, christine]
heights = [rayHeight, vickiHeight, gregHeight,micHeight,christineHeight]
widths = [rayWidth, vickiWidth, gregWidth,micWidth,christineWidth]
for image in razeware {
var tapGesture = UITapGestureRecognizer(target: self, action: "tappedImage:")
image.userInteractionEnabled = true
image.addGestureRecognizer(tapGesture)
}
}
func tappedImage(sender:UITapGestureRecognizer!) {
var tag = 0
// index / tag who's been tapped
if let senderTag = sender.view?.tag {
tag = senderTag
}
let width = widths[tag] // get the width constraint from the array
let height = heights[tag]
print(width)
view.setNeedsUpdateConstraints()
if previousHeight == height {
if previousHeight?.constant == 100 {
previousHeight?.constant = 50
previousWidth?.constant = 50
print("through here")
//UIView.animateWithDuration(3.0, animations: { () -> Void in
self.name.text = ""
self.bio.text = ""
self.emailButton.hidden = true
// self.view.layoutIfNeeded()
// })
} else {
previousHeight?.constant = 100
previousWidth?.constant = 100
print("Going here")
name.text = names[tag]
bio.text = bios[tag]
bio.font = UIFont.systemFontOfSize(15.0)
bio.textColor = UIColor.whiteColor()
emailButton.hidden = false
}
} else {
previousHeight?.constant = 50
previousWidth?.constant = 50
UIView.animateWithDuration(5.0, animations: { () -> Void in
width.constant = 100
height.constant = 100
self.name.text = self.names[tag]
self.bio.text = self.bios[tag]
self.bio.font = UIFont.systemFontOfSize(15.0)
self.bio.textColor = UIColor.whiteColor()
self.emailButton.hidden = false
self.view.layoutIfNeeded()
})
}
print(width)
previousHeight = height
previousWidth = width
print("Previous: \(previousHeight)")
print("Height: \(height)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Even if a constraint was re-defined in code elsewhere previously, layoutIfNeeded() will revert to the original IB defined constraint value - unless the constraint is re-defined again (to maintain its new value) after setNeedsUpdateContraints().
This is based on a lot of trial an even more error. Perhaps there is still a chance for a better answer...

Dynamically Calculate Pace in Swift

I have this code below. How would dynamically calculate the pace as I fill in the fields instead of having to calculate it manually by tapping on the Calculate Pace button?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var minTextField: UITextField!
#IBOutlet weak var secTextField: UITextField!
#IBOutlet weak var distTextField: UITextField!
#IBOutlet weak var paceLabel: UILabel!
func paceInSeconds (minutes:Double, seconds: Double, distance: Double) -> Double {
return ((minutes*60) + seconds) / distance
}
#IBAction func paceCalculator(sender: UIButton) {
var paceMinutes = paceInSeconds(((minTextField.text as NSString).doubleValue, seconds: (secTextField.text as NSString).doubleValue, distance: (distTextField.text as NSString).doubleValue)) / 60
var roundedPaceMinutes = Double(floor(paceMinutes))
var decimalPaceSeconds = paceMinutes - roundedPaceMinutes
var intPaceMinutes = Int(floor(roundedPaceMinutes))
var paceSeconds = Int(floor(decimalPaceSeconds * 60))
var paceSecondsZero = String(format: "%02d", paceSeconds)
paceLabel.text = "\(intPaceMinutes):\(paceSecondsZero)/km"
}
}
Here's the storyboard UI:
You can use the various functions of the UITextFieldDelegate protocol. If you assign your view controller as the delegate of the text field, it will be able to act upon changes in the text field.
In your case, you should implement the textField:shouldChangeCharactersInRange:replacementString: function.

Resources