I have a simple app that has 3 text fields, a label and a button. User would enter text into the 3 text fields and then press the button. The text from one of the text fields would randomly be selected and applied as the text to a label.
I’ve tried using something like
let textArray : String [text1, text2, text3]
For the array but this doesn’t seem to be working. Can someone nudge me in the right direction?
You can take an array and add textfield text into that array.
var textFieldArray: [String] {
return [textfield1.text!, textfield2.text!, textfield3.text!]
}
Then generate a random number using the code below:
func RandomInt(min: Int, max: Int) -> Int {
if max < min { return min }
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}
Now get the random text using the index path of the array.
let randomNumber = RandomInt(min: 1, max: 3)
let randomText = textFieldArray[randomNumber]
labelName.text = randomText
Not sure if I understand. You probably want this:
var textArray: [String] {
return [textfield1.text, textfield2.text, textfield3.text]
}
Related
I will get array of strings those strings need to display with border in swift iOS.
Example:
let tags = ["Draft", "Sent", "Inbox"]
The above list need to convert as a flat string and display in single line as shown in below
Expected output with border draft image:
Draft Sent Inbox // All tags should have border like below also text colour should be different
I tried with below it works upto making single line string how to create border for each along with different colour.
func mergeTags(tags: [String]) -> String {
let tagsList : String = tags.reduce("", { $0 == "" ? $1 : $0 + " " + $1 })
return tagsList
}
my problem is I want to put 2 placeholders for one textField. one of the place holders should be on the left and the other should be on the right.
my code:
func returnPlaceHolder(first: String, second: String, textField: UITextField){
let width: Int = Int(textField.bounds.width * 0.2)
let spaceValue = width - (first.count + second.count)
var temp = "\(first) "
let tempCount = spaceValue - (first.count + second.count)
var value = String()
for _ in 0..<tempCount {
temp.append(" ")
}
value = "\(temp) \(second)"
textField.placeholder = value
textField.setLeftPaddingPoints(10)
textField.setRightPaddingPoints(10)
}
I'm currently using this function to create spaces.. but my problem is the spaces won't be the same for more than one textField, and I want them to be aligned..
just like this picture: https://imgur.com/pZZMoNv
and this is the result I'm getting for my current code: https://imgur.com/a/5AN8EXl
don't mind the textFields format & text I can fix them later.. I just want to be able to align the textFields placeholders.
It would be really hard (if possible) to achieve what you are trying to do by injecting spaces into the text because each character in the font has a different width unless you use a monospaced font.
https://en.wikipedia.org/wiki/Monospaced_font
Instead, I would recommend a different approach. Override the text field, provide two UILabels and adjust their position using Autolayout.
I am trying to make an image view set to a certain image when a label displays a certain word from an array which is being randomised.
The picture is supposed to set to the image view when specific words are the text of the label from the array.
Here is the array:
let freeMoodArray = ["Happy", "Sad", "Angry", "Annoyed", "Curious", "Bored", "Chilled", "Furious", "Excited", "Scared", "Emotionless", "Shocked", "Tired", "Sick", "Amused"]
Here is the random label text:"
self.moodAnswer.text = "\(self.freeMoodArray.randomElement()!)"
Now when I load the view, the image chooses a random word from the array which is working. Now, lets say it says Happyas the text of the label.
I want to set a certain image only when it says happy.
Here is my code, which doesn't work: (this func is called in the viewDidLoad())
func emojiMood() {
if moodAnswer.text == "Happy" {
emojiImg.image = UIImage(named: "happy.png")
}
}
how a but a variable and DidSet ?
// create a variable
var moodAnswer : string = "" {
didSet {
// if or switchCase, set image only if the text is equal to Happy
if moodAnswer == "Happy" {
emojiImg.image = UIImage(named: "happy.png")
}
// always set text field with new updated text
self.moodAnswerLabel.text = moodAnswer
}
}
// in your code always set moodAnswer variable, this is more clean and also you set label and image only in a single place
self.moodAnswer = "\(self.freeMoodArray.randomElement()!)"
I am trying to create a read more button at the end of my label. I want it to display 3 lines by default. I am coding in swift not objective c. Only when the user clicks the read more part of the label, should the label expand. It should look and work exactly like it does on instagram except on Instagram, it is in a tableview cell. My label and read more button will be in a scrollview. I have managed to get the expanding and contracting part working by adjusting the number of lines property of the label.
if descriptionLabel.numberOfLines == 0{
descriptionLabel.numberOfLines = 3
}else {
descriptionLabel.numberOfLines = 0
}
descriptionLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
I am having problems with putting a "...more" at the end of the label and cutting the text off at the right place. I have looked at other people's responses to similar questions but nothing seems to work properly.
I can put a button over the last line of text so making the see more part of the label clickable also isn't the problem. The problem I am having is truncating the text at the right place and placing the see more text at the right place so that it displays.
I also want the read more button to only appear when it is necessary. I don't want to it appear when there are only 1-3 lines of text. This is also something I am having issues with.
I can't use this https://github.com/apploft/ExpandableLabel because it does not support scrollviews just tableviews.
the swift solution here didn't work: Add "...Read More" to the end of UILabel. It crashed the app.
Finally, the read more button should be in line with the last line of text and at the end of it. It would be an added benefit it this worked in a tableview cell as well!
I found ReadMoreTextView in Github, which is based on UITextView. The key method in this library is the following:
private func characterIndexBeforeTrim(range rangeThatFits: NSRange) -> Int {
if let text = attributedReadMoreText {
let readMoreBoundingRect = attributedReadMoreText(text: text, boundingRectThatFits: textContainer.size)
let lastCharacterRect = layoutManager.boundingRectForCharacterRange(range: NSMakeRange(NSMaxRange(rangeThatFits)-1, 1), inTextContainer: textContainer)
var point = lastCharacterRect.origin
point.x = textContainer.size.width - ceil(readMoreBoundingRect.size.width)
let glyphIndex = layoutManager.glyphIndex(for: point, in: textContainer, fractionOfDistanceThroughGlyph: nil)
let characterIndex = layoutManager.characterIndexForGlyph(at: glyphIndex)
return characterIndex - 1
} else {
return NSMaxRange(rangeThatFits) - readMoreText!.length
}
}
To display text like "xxxx...Read More", the library
Get how many characters could be display in the UITextView: Use NSLayoutManager.characterRange(forGlyphRange:, actualGlyphRange:)
Get the position of the last visible character and the width of "...Read More": Use NSLayoutManager.boundingRect(forGlyphRange glyphRange: NSRange, in container: NSTextContainer)
Get the character index before trimming: Use NSLayoutManager.characterIndexForGlyph(at glyphIndex: Int)
Replace text which should be trimmed with "...Read More": UITextStorage.replaceCharacters(in range: NSRange, with attrString: NSAttributedString)
Please check :
func addSeeMore(str: String, maxLength: Int) -> NSAttributedString {
var attributedString = NSAttributedString()
let index: String.Index = str.characters.index(str.startIndex, offsetBy: maxLength)
let editedText = String(str.prefix(upTo: index)) + "... See More"
attributedString = NSAttributedString(string: editedText)
return attributedString
}
You can use like :
let str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
descriptionLabel.attributedText = addSeeMore(str: str, maxLength: 20)
// Output : Lorem Ipsum is simpl... See More
I have UITextField with long placeholder like this:
"QWERTYUIOPASDFGHJKLZXCVBNM", but my textfield is small and when I use function textField.adjustsFontSizeToFitWidth = true the minimumFontSize that I can set is 9 but still I can't fit the text into the textField. I want to cut the middle of the text and I expect the text to be "QWERTY...CVBNM" how to do that?
func cutTheMiddleOfLongString(var string:String) -> String {
if(countElements(string)>20){
let begining = string[advance(string.startIndex, 0)..<advance(advance(string.startIndex, 0), 12)]
let ending = string[advance(string.startIndex, countElements(string)-8)..<advance(advance(string.startIndex, countElements(string)-8), 8)]
string = begining + "..." + ending
}
return string
}
This will take first 12 letters and last 8 letters of the string and will put ... between them(begining ending).