Unable to copy text from UILabel in Swift - ios

I have to delete an entry from a UILabel. I am doing so by copying its text to a string variable and deleting the end index to the string. The UILabel does contain a value but the string it is being copied to contains nothing. Any help would be most appreciated.
var displayString = display.text!
displayString.removeAtIndex(displayString.endIndex) //error at this line.
display.text! = displayString
The state of the string can be seen in this screenshot.
and the debugger can be seen here that the display UILabel actually does contain the string.

You should not remove the endIndex, but the one before the end. And you should only remove something from the string if there actually is something to remove - check for the empty string before removing a character:
if displayString != "" {
displayString.removeAtIndex(displayString.endIndex.predecessor())
}

Related

Insert line break for UILabel text when a specific character is found

I have a UILabel that dynamically gets updated every time I click a button, the data will be fetched from firebase and displayed on the uilabel.I am able to display the text as shown below. I would like to insert a line break when a specific delimiter(say '.' PERIOD) is encountered in the text. I have looked into many solutions about UIlabel line break but couldn't find one what exactly I am looking for, every solution deals with static text that we provide in the storyboard itself. Any help will be appreciated. Thank you.
)
Created an outlet for the label and have taken a string which has three sentences separated by ".". The content in the image attached will be this string. Try using replacingOccurences() function as given below.
#IBOutlet weak var trialLabel: UILabel!
var string = "This is a trial text.Let us jump to a new line when the full stop is encountered.Hope it helps."
string = string.replacingOccurrences(of: ".", with: ".\n")
trialLabel.text = string
Check https://developer.apple.com/documentation/foundation/nsstring/1412937-replacingoccurrences for further reference. Happy Coding!!
You can achieve this with the attributed text property of UILabel. Try to find and replace the character with html line break and then assign this text to the UILabel attributed text.
You can replace string by
let str = "This is the string to be replaced by a new string"
let replacedStr = str.replacingOccurrences(of: "string", with: "str")
use below code
// HTML Tag Remove Method
extension String{
func removeHtmlFromString(inPutString: String) -> String{
return inPutString.replacingOccurrences(of: ".", with: ".\n", options: .regularExpression, range: nil)
}
}
let str = "Lorem Ipsum is simply dummy text.Lorem Ipsum has been the industry's standard dummy text ever since the 1500."
let postDiscription = str!.removeHtmlFromString(inPutString: str!)
You can add a \n in the text string to where you want to create a line break.

UILabel won't display specific String variable in Swift

I have an array containing string type values, and one value of a string contains the symbol & and another the symbol ^. So when it's time for them to be shown the UILabel remains blank.
let myString = arrayStrings[0] // The value is "M&M" or "(0C)^3"
myLabel.text = myString //UILabel remains blank
On the other hand, when I hardcode the string, the UILabel displays it.
myLabel.text = "M&M" //UILabel displays it normally
What can I do?
Just realised that when I print the Array I have the following result:
print("Array: \(arrayStrings)" // Array: ["\0M&M\0", "\0(0C)^3\0"]
"\0" doesn't exist to the rest Strings of the array
Thank you!
\0 means string termination in programming. So your String "\0M&M\0" means that this string is terminated on index 0, and then again later. So when you assign this string to your label, your label is displaying empty string.
To tweak it, do this and you will see the difference. Your problem is not related to & or ^
myLabel.text = "M&M\0 Hey I have lots of stuff here but the string is already terminated"
So in this situation, you need to find out why \0 exists in your string. You can possibly remove them by regex or string replace.

UIlabel text does not show "optional" word when setting optional text?

I have been using optional a lot.I have declared a string variable as optional
var str: String?
Now i set some value in this variable as str = "hello".Now if i print this optional without unwrapping then it print as
Optional("hello")
But if i set text on the label as self.label.text = str then it just display value as
hello
Please explain why it does not show text as on label
Optional("hello")
The text property of UILabel is optional. UILabel is smart enough to check if the text property's value is set to nil or a non-nil value. If it's not nil, then it shows the properly unwrapped (and now non-optional) value.
Internally, I imagine the drawRect method of UILabel has code along the lines of the following:
if let str = self.text {
// render the non-optional string value in "str"
} else {
// show an empty label
}
I knew I've seen optionals printed in UILabel, UITextView, UITextField. Rmaddy's answer wasn't convincing.
It's very likely that there is an internal if let else so if the optional has a value then it will unwrap it and show. If not then it would show nothing.
However there's a catch!
let optionalString : String? = "Hello World"
label.text = "\(optionalString)" // Optional("Hello World")
label.text = optionalString // Hello World
let nilOptionalString : String?
label.text = "\(nilOptionalString)" // `nil` would be shown on the screen.
label.text = nilOptionalString // no text or anything would be shown on the screen . It would be an empty label.
The reason is that once you do "\(optionalVariable)" then it would go through a string interpolation and once its a String and not String? then the result of the interpolation would be shown!

Getting the First Letter of a String in Hebrew

In a UITableView, I'm listing a bunch of languages to be selected. And to put a section index view to the right like in Contacts app, I'm getting all first letters of languages in the list and then use it to generate the section index view.
It works almost perfect, Just I encountered with a problem in getting first letter of some strings in Hebrew. Here a screenshot from playground, one of the language name that I couldn't get the first letter:
Problem is, the first letter of the name of the language that has "ina" language code, isn't "א", it's an empty character; it's not a space, it's just an empty character. As you can see, it's actually 12 characters in total, but when I get count of it, it says 13 characters because there is an non-space empty character in index 0.
It works perfectly if I use "eng" or "ara" languages with putting these values in value: parameter. So maybe the problem is cause of system that returns a language name with an empty character in some cases, I don't know.
I tried some different methods of getting first letter, but any of it didn't work.
Here "א" isn't the first letter, it's the second letter. So I thought maybe I can find a simple hack with that, but I want to try solving it before trying workarounds.
Here is the code:
let locale = NSLocale(localeIdentifier: "he")
let languageName = locale.displayNameForKey(NSLocaleIdentifier, value: "ina")!
let firstLetter = first(languageName)!
println(countElements(languageName))
for character in languageName {
println(character)
}
You could use an NSCharacterSet.controlCharacterSet() to test each character. I can't figure out how to stay in Swift-native strings, but here's a function that uses NSString to return the first non-control character:
func firstNonControlCharacter(str: NSString) -> String? {
let controlChars = NSCharacterSet.controlCharacterSet()
for i in 0..<str.length {
if !controlChars.characterIsMember(str.characterAtIndex(i)) {
return str.substringWithRange(NSRange(location: i, length: 1))
}
}
return nil
}
let locale = NSLocale(localeIdentifier: "he")
let languageName = locale.displayNameForKey(NSLocaleIdentifier, value: "ina")!
let firstChar = firstNonControlCharacter(languageName) // Optional("א")

Multi-line string formatting issue in UILabel

I want my label to read like this:
Name of Activity
nn%
Instead, here's what appears:
%#
%f%
In addition, I'm getting this warning: Expression result unused
Here's the code I'm trying:
firstLabel.text = #"%#\n%#%",[self.thisSpec activityOfInterest],focusActivityPercent;
[self.thisSpec activityOfInterest] returns a string containing the name of an activity, and focusActivityPercent is a double.
This is the first time I've tried a multiline label.
Any suggestions?
Thanks
You can't specify string formatting on a string literal on its own like that. In fact, the code you've shown should be producing a syntax error. You have to use NSString's stringWithFormat: class method:
firstLabel.text = [NSString stringWithFormat:#"%#\n%#%",[self.thisSpec activityOfInterest],focusActivityPercent];

Resources