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.
Related
I am trying to use an iOS app to dial a number. The problem is that the number is in the following format:
po placeAnnotation.mapItem.phoneNumber!
"+1 (832) 831-6486"
I want to get rid of some special characters and I want the following:
832-831-6486
I used the following code but it did not remove anything:
let charactersToRemove = CharacterSet(charactersIn: "()+-")
var telephone = placeAnnotation.mapItem.phoneNumber?.trimmingCharacters(in: charactersToRemove)
Any ideas?
placeAnnotation.mapItem.phoneNumber!.components(separatedBy: CharacterSet.decimalDigits.inverted)
.joined()
Here you go!
I tested and works well.
If you want something similar to CharacterSet with some flexibility, this should work:
let phoneNumber = "1 (832) 831-6486"
let charsToRemove: Set<Character> = Set("()+-".characters)
let newNumberCharacters = String(phoneNumber.characters.filter { !charsToRemove.contains($0) })
print(newNumberCharacters) //prints 1 832 8316486
I know the question is already answered, but to format phone numbers in any way one could use a custom formatter like below
class PhoneNumberFormatter:Formatter
{
var numberFormat:String = "(###) ### ####"
override func string(for obj: Any?) -> String? {
if let number = obj as? NSNumber
{
var input = number as Int64
var output = numberFormat
while output.characters.contains("#")
{
if let range = output.range(of: "#", options: .backwards)
{
output = output.replacingCharacters(in: range, with: "\(input % 10)")
input /= 10
}
else
{
output.replacingOccurrences(of: "#", with: "")
}
}
return output
}
return nil
}
func string(from number:NSNumber) -> String?
{
return string(for: number)
}
}
let phoneNumberFormatter = PhoneNumberFormatter()
//Digits will be filled backwards in place of hashes. It is easy change the custom formatter in anyway
phoneNumberFormatter.numberFormat = "###-##-##-##-##"
phoneNumberFormatter.string(from: 18063783889)
Swift 3
func removeSpecialCharsFromString(_ str: String) -> String {
struct Constants {
static let validChars = Set("1234567890-".characters)
}
return String(str.characters.filter { Constants.validChars.contains($0) })
}
To Use
let str : String = "+1 (832) 831-6486"
let newStr : String = self.removeSpecialCharsFromString(str)
print(newStr)
Note: you can add validChars which you want in string after operation perform.
If you have the number and special character in String format the use following code to remove special character
let numberWithSpecialChar = "1800-180-0000"
let actulNumber = numberWithSpecialChar.components(separatedBy: CharcterSet.decimalDigit.inverted).joined()
Otherwise, If you have the characters and special character in String format the use following code to remove special character
let charactersWithSpecialChar = "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!"
let actulString = charactersWithSpecialChar.components(separatedBy: CharacterSet.letters.inverted).joined(separator: " ")
NSString *str = #"(123)-456-7890";
NSLog(#"String: %#", str);
// Create character set with specified characters
NSMutableCharacterSet *characterSet =
[NSMutableCharacterSet characterSetWithCharactersInString:#"()-"];
// Build array of components using specified characters as separtors
NSArray *arrayOfComponents = [str componentsSeparatedByCharactersInSet:characterSet];
// Create string from the array components
NSString *strOutput = [arrayOfComponents componentsJoinedByString:#""];
NSLog(#"New string: %#", strOutput);
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.
I am doing a project in Swift and I am reading data from a file and trying to display it in a text view. I am reading it line by line. For example, if I have 10 lines in the file the text view only shows the last one. And I'd like to see them all.
How can I do that?
I am doing it like this:
if let aStreamReader = StreamReader(path: "historic.txt") {
defer {
aStreamReader.close()
}
while let line = aStreamReader.nextLine() {
MyTextView.text = "\(line)"
}
The code is working in the console, because if I make a print every show up ok.
But in the text view only last line is visible.
How about trying:
MyTextView.text += "(line)"
The '+' will append rather than replace.
You might have to add \n after the lines string to create a new line:
MyTextView.text += "(line) \n"
Update:
I forgot you can't append onto a textview, so instead create an empty string before the loop and then append the line onto the string in the while loop. Then finally set the textview text to the totalString variable after the loop:
var totalString = ""
while let line = aStreamReader.nextLine() {
totalString = totalString + line + "\n"
}
MyTextView.text = totalString
Hope that helps
Make sure the value of lines property of label is 0 and try this
if let aStreamReader = StreamReader(path: "historic.txt") {
defer {
aStreamReader.close()
}
var str = ""
while let line = aStreamReader.nextLine() {
str = str + line + "\n"
}
MyTextView.text = str
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!
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;"
}