String formatting in Swift - ios

I can't seem to understand why the following does not work:
var content : NSString = ""
let myLabel : UILabel = self.view.viewWithTag(i) as UILabel
content += String(format:"var %# = false;", myLabel.text)
I get the following error:
NSString is not identical to 'UInt8'

It's because NSString class doesn't support appending string using +. It only supports if you use String. You can fix that issue by:
var content : String = ""
let myLabel : UILabel = self.view.viewWithTag(i) as UILabel
content += String(format:"var %# = false;", myLabel.text!)

try using String interpolation:
content += "var \(myLabel.text) = false;"

Instead of using format, why not use Swift's string interpolation?
content += "var \(myLabel.text!) = false;"
It doesn’t give you the numeric formatting that is so useful in NSString's format, but you are just inserting a string with no formatting required.
However the use of ! without checking always makes me twitch, so how about something like:
if let labelText = myLabel.text {
content += "var \(labelText) = false;"
}

Related

Add '...' After UILabel Word Wrapped Property

I have a UILabel that has max-lines of 2, and a word wrapping property. This is done in storyboard.
I need to add a '...' after the last wrapped word on those labels that end up being word wrapped.
Is this possible? I have tried some solutions from around the internet, but they seem to have not worked. Those include:
Testing label if it has been truncated, and appending '...' to those that have been.
Programmatically using attributed text to hijack storyboard.
Tried using Truncate Tail - Unable to use this because it cuts the word off like so "Highli...".
I think I understand what you are trying to do. This is a bit sloppy, but it should work
extension UILabel {
func truncateAndFitText()
{
if let string = self.text
{
let words = string.components(separatedBy: " ")
var lastString = ""
var tempString = ""
for word in words
{
(tempString == "") ? tempString.append(word) : tempString.append(" \(word)")
let size: CGSize = tempString.size(attributes: [NSFontAttributeName: self.font])
if (size.width > (self.bounds.size.width * CGFloat(self.numberOfLines)))
{
lastString.append("...")
break
}
else
{
lastString = tempString
}
}
self.text = lastString
}
}
}
and then use it like
myLabel.truncateAndFitText

UILabel shows Optional("P")

I have a UILabel where i set its texts property, and
let firstCharacter: String = "\(user.name.characters.first)" ?? ""
print(firstCharacter)
userNameLabel.text = firstCharacter
Output: Optional("P")
String Interpolating user.name.characters.first will always create a String because even if user.name.characters.first is nil then the interpolated string will be "nil".
The correct solution is
userNameLabel.text = "" //set the default value as ""
//if the name contains atleast one char then set it
if let firstCharacter = user.name.characters.first {
userNameLabel.text = "\(firstCharacter)"
}
Wrap optional like so:
if let userName = user.name.characters.first {
userNameLabel.text = userName
}
IF you need to get first character you can use following code and it would be more correct than taking first character
let firstCharacter = user.name.substringToIndex(user.name.startIndex.advancedBy(1))
But note that you need to check before this call if the string is not empty.
Print like this.
println(firstCharacter!)
it will work.

Line break in UILabel (Xcode 7 Swift)

So I have an array of elements of type float. And I have a UILabel which is supposed to display each of these elements of the array on DIFFERENT LINES.
The Array is
var history = [Float]()
I used a for loop to go through each element and append it to the UILabel
for(i=0; i<size; i++){
currentString = String(history[i])
result.text = result.text! + "\n" + currentString
}
result is the UILabel.
I tried using \n but it doesn't seem to recognise it. Any solutions for this in Swift. Thanks in advance!
You can try below to solve your issue.
let history = [1.0, 2.0, 3.0, 4.0]
var result = ""
self.lbl.text = ""
for var i=0; i < history.count; i++
{
let currentString = NSString(format: "%.2f", history[i])
self.lbl.text = self.lbl.text! + "\n" + (currentString as String)
}
And Line Number should be 0. I set that from XIB.
Thanks
The first thing I would check is if your label has (it is stupid mistake, but can happen to all of us)
label.numberOfLines = 0
Assuming that is true, instead of building the string by hand, you could use in-built function join(). Sadly, since it is not String array, you can't use it directly, but you have to create string array first
// Get both storages
var history = [Float]() // Filled with your data
var stringHistory = [String]()
// Convert each number to string
for value in history {
stringHistory.append(String(value))
}
// Finally, join array to one string using \n as separator
let finalString = "\n".join(stringHistory)
Hope some of this helps!

Append String in Swift

I am new to iOS. I am currently studying iOS using Objective-C and Swift.
To append a string in Objective-C I am using following code:
NSString *string1 = #"This is";
NSString *string2 = #"Swift Language";
NSString *appendString=[NSString stringWithFormat:#"%# %#",string1,string2];
NSLog(#"APPEND STRING:%#",appendString);
Anyone please guide me.
Its very simple:
For ObjC:
NSString *string1 = #"This is";
NSString *string2 = #"Swift Language";
ForSwift:
let string1 = "This is"
let string2 = "Swift Language"
For ObjC AppendString:
NSString *appendString=[NSString stringWithFormat:#"%# %#",string1,string2];
For Swift AppendString:
var appendString1 = "\(string1) \(string2)"
var appendString2 = string1+string2
Result:
print("APPEND STRING 1:\(appendString1)")
print("APPEND STRING 2:\(appendString2)")
Complete Code In Swift:
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING1:\(appendString1)")
print("APPEND STRING2:\(appendString2)")
In Swift, appending strings is as easy as:
let stringA = "this is a string"
let stringB = "this is also a string"
let stringC = stringA + stringB
Or you can use string interpolation.
let stringC = "\(stringA) \(stringB)"
Notice there will now be whitespace between them.
Note: I see the other answers are using var a lot. The strings aren't changing and therefore should be declared using let. I know this is a small exercise, but it's good to get into the habit of best practices. Especially because that's a big feature of Swift.
let string2 = " there"
var instruction = "look over"
choice 1 :
instruction += string2;
println(instruction)
choice 2:
var Str = instruction + string2;
println(Str)
ref this
Add this extension somewhere:
extension String {
mutating func addString(str: String) {
self = self + str
}
}
Then you can call it like:
var str1 = "hi"
var str2 = " my name is"
str1.addString(str2)
println(str1) //hi my name is
A lot of good Swift extensions like this are in my repo here, check them out: https://github.com/goktugyil/EZSwiftExtensions
You can simply append string
like:
var worldArg = "world is good"
worldArg += " to live";
var string1 = "This is ";
var string2 = "Swift Language";
var appendString = string1 + string2;
println("APPEND STRING: \(appendString)");
According to Swift 4 Documentation,
String values can be added together (or concatenated) with the addition operator (+) to create a new String value:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
You can also append a String value to an existing String variable with the addition assignment operator (+=):
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
You can append a Character value to a String variable with the String type’s append() method:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
> Swift2.x:
String("hello ").stringByAppendingString("world") // hello world
Strings concatenate in Swift language.
let string1 = "one"
let string2 = "two"
var concate = " (string1) (string2)"
playgroud output is "one two"
In the accepted answer PREMKUMAR there are a couple of errors in his Complete code in Swift answer. First print should read (appendString) and Second print should read (appendString1). Also, updated println deprecated in Swift 2.0
His
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
println("APPEND STRING1:\(appendString1)")
println("APPEND STRING2:\(appendString2)")
Corrected
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING:\(appendString)")
print("APPEND STRING1:\(appendString1)")
SWIFT 2.x
let extendedURLString = urlString.stringByAppendingString("&requireslogin=true")
SWIFT 3.0
From Documentation:
"You can append a Character value to a String variable with the String type’s append() method:" so we cannot use append for Strings.
urlString += "&requireslogin=true"
"+" Operator works in both versions
let extendedURLString = urlString+"&requireslogin=true"
let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"

IOS insert line break to data retrieved from parse.com

i am trying to retrieve some string data from parse.com and i've added "\n, \n & \r" into the data, but it still does not give me the line breaks, how do format the line below to get line breaks.
self.label.text = [NSString stringWithFormat:#"%#", [object objectForKey:#"ParseStringDate"]];
if you get the text that should be presented in multiple lines then you should try to set for your label this property:
self.label.numberOfLines = 0;
it basically means that label can be multiline, make sure that frame of that label is sufficient to show more that one line of text
if some has the same challenge in swift - please find attached a short string extension:
extension String {
func formatStringFromParseWithLineBreaks() -> String {
let sourceString: String = self
let resultString = sourceString.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
return resultString
}
}
It is easy to use:
let stringFromParse = "Great\\nExample"
let newString = stringFromParse.formatStringFromParseWithLineBreaks()
Have fun
self.label.text = [NSString stringWithFormat:#"first\n%#\n another", [object objectForKey:#"ParseStringDate"]];
Make sure you have numberOfLines of the label set to 0. This should work.

Resources