I'm new to swift and I am trying to understand UILabel text property
Based on what I have read, my understanding is that I can replace text with any String . So I did
The text property is "read-only" , is there a way I can change text label by hardcoding in swift ?
I am not in front of my computer to verify this, but I don't think you need to mark it as "self"
Just Food.text = "Burger"
Additionally. It is common for you to put variables with the first letter as lower case with each other words first letter being upper case
For example.
var firstWord = "Traditionally the best way to code"
Capital first letter first word is traditionally used for classes.
Example
Class NewClass = "Blah Blah"
You cannot set a value like this in the declaration section of the class.
Since you're working with a UIViewController, you'll want to go to the viewDidLoad() method and put self.Food.text = "Burger" there.
For example:
import UIKit
class TestViewController: UIViewController {
#IBOutlet weak var Food: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.Food.text = "Burger"
}
}
The viewDidLoad() method is called by the system when (coincidentally enough) the view is first loaded. After the view has loaded, you are free to make any edits to any of the objects on the screen. viewDidLoad will be where you will want to perform the majority of the setting up of your view.
100% programatically would be like this. This both creates the label and the string.
override func viewDidLoad()
{
super.viewDidLoad()
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "Burger"
self.view.addSubview(label)
}
Related
Scenario: I merely want to able to fit a string within a UILabel per target device.
That is, on one iPad model the string is truncated. On another it isn't.
I suspect the application is more code-centric vs IB. So I want to be able to work with the UILabel programmatically.
Here's the code:
class ViewController: UIViewController {
#IBOutlet var myLabel: UILabel!
#IBAction func addMessageAction(_ sender: UIBarButtonItem) {
let msg = "Mother had a feeling, I might be too appealing. But I can understand."
myLabel.text = msg
myLabel.numberOfLines = 0
myLabel.adjustsFontForContentSizeCategory = true
myLabel.sizeToFit()
myLabel.lineBreakMode = .byTruncatingTail
myLabel.minimumScaleFactor = 0.5
}
#IBAction func exitAction(_ sender: UIBarButtonItem) {
exit(0)
}
}
Here's the screen after I pressed the 'message' button:
This only appear to work with I set the UILabel properties within IB.
Why doesn't it work via code?
I tried your code and its working perfectly. Is there any Autolayout constraint mismatch ?
You can do one thing to this change the font size to fit the width of the label
myLabel.adjustsFontSizeToFitWidth = true
Debashish gave me the correct answer.
I added his suggestion: myLabel.adjustsFontSizeToFitWidth = true and it worked in real time.
Interestingly, I had used the original code snippet in a shared project; and it worked...but not in my small proof-of-concept.
But again, the added myLabel property statement did the trick here.
Okay, this might be one of the most basic questions ever, but all answers I find use storyboard to declare an outlet for a label, textfield or whatever element that needs to be changed. I, however, don't use storyboards and write everything in code. Now I have a function setupViews, where I define a textfield:
let usernameInput = UITextField()
Now, I can perfectly set the text or placeholder or whatever inside this setupViews() class, but how can I access it outside? For example, if I have a function logIn(), I want to call usernameInput.text and use it in this function.
Someone who can point me in the right direction? Do I need to declare this textfield globally, in another file, or something else?
When I create my views in code I always associate a property with the view that has all those various display values.
I have not tested this code to see but hopefully the following will give you an idea.
import UIKit
struct {
var name: String
}
class CustomViewController : UIViewController {
// some struct which contains data for view
var customViewData : ViewDataInfo? {
didSet {
labelOnScreen.text = customViewData.name
}
}
var labelOnScreen: UILabel = {
let label = UILabel()
label.text = "Placeholder information..."
// stuff auto layout
label.translateAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
private func setupView() {
view.addSubview(label)
// set your constraints here
}
}
I am trying to print a uiview in a label. I don't know if I should put accessibilityIdentifier or not. When I did put accessiblitiyIdentifier in my whole app loaded but was all black.
#IBOutlet var pink: UIView!
#IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = pink
}
AccessibilityIdentifier can use for UI Automation scripts,
label.text = pink wont be compile
you can use label.addSubview(pink)
label.text is of type String and pink is of type UIView!, that shouldn't even compile?
The code I am using:
#IBOutlet weak var tlabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tlabel.font = UIFont(name: "Anxiety", size: 40)
tlabel.numberOfLines = 0
tlabel.text = "Test"
}
The text "Test" gets capitalized ("TEST" appears on the screen). How can I avoid this?
A quick google seems to show that the font Anxiety does not have any non capital letters in the font. So if you want to use non capital letters you have to find another font.
http://www.1001freefonts.com/anxiety.font
I'm adding a few UISteppers and UITextFields programmatically, based on user's preferences. However, I can't seem to get the UIStepper touch to click - it looks like it's not registering the touch on the -/+ buttons. I tried setting User Interaction of the userTriggers UIView to disabled, but that didn't work.
1) What else can I try?
2) I also need to be able to increment the corresponding UITextField, and then write that into my UserData.plist file, and I'm not sure how to access each field. Should I add them to an array of some sort?
import UIKit
class TriggersViewController: UIViewController{
#IBOutlet var userTriggers:UIView!
#IBOutlet var saveButton:UIButton!
var triggersList:Array<String>!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadTriggers()
var prevInput = 250;
for index in 0..<triggersList.count{
//label for trigger
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(120, CGFloat(prevInput))
label.textAlignment = NSTextAlignment.Left
label.text = triggersList[index]
userTriggers.addSubview(label)
//input box for trigger
var input = UITextField(frame: CGRectMake(0, 0, 50, 21))
input.center = CGPointMake(250, CGFloat(prevInput))
input.text = "0";
//add input to triggersView
userTriggers.addSubview(input);
//UIStepper
var stepper = UIStepper(frame: CGRectMake(0, 0, 50, 21))
stepper.center = CGPointMake(300, CGFloat(prevInput))
stepper.addTarget(self, action: "stepperValueChanged:", forControlEvents: .ValueChanged)
stepper.enabled = true
//add stepper to triggersView
userTriggers.addSubview(stepper);
prevInput += 50 //increment for height
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func stepperValueChanged(sender:UIStepper!){
println("It Works, Value is -->\(Int(sender.value).description)")
}
func loadTriggers(){
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("UserConfigs", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
triggersList = dict["Triggers"] as Array<String>
}
}
}
You actually need to set user interaction on the superview to enabled. See here for more info: UIView -- "user interaction enabled" false on parent but true on child?
Also, re: second question an easy (but not so ideal) way to access each field is using tags. Clean-ish way to do that is define tags using an enum. Then access the fields using viewWithTag.
However, there are better ways than tags (e.g. they're not very error-proof because any view can be given any tag). If it's only a few text fields / steppers though you could just as easily add properties to your view controller for each one. The best solution would be to group the steppers and fields together in a UIView subclass (assuming they're next to each other) and store references to those groupings in your view controller (possibly in an array).