I'm struggling a little bit with attributed strings in Appcelerator and was hoping for some assistance.
So, I have a couple of scenarios.
I use an API to retrieve user information, but the app needs to display said username with an @ in front of it and be in a different colour to the rest of the string. Now this is ok for the screens that have the username at the beginning, but unfortunately I can't get it to work mid string.
Here is the current code:
var attr = Ti.UI.createAttributedString({
text: '@' + text,
attributes: [{
type: Ti.UI.ATTRIBUTE_FOREGROUND_COLOR,
value: '#ff3333',
range: [text.indexOf(userToHighlight), (userToHighlight).length+1]
}]
});
var notificationMessage = Ti.UI.createLabel({
attributedString: attr,
left: 0,
top: 5,
font: {
fontFamily: 'OpenSans-Light',
fontSize: 13
}
});
And this is what the output should look like in the different scenarios....
So, the conditions for those strings are as follows....
Scenario 1 is ok, but scenario 2 currently looks like this...
@You are now friends with username
So the @ is at the beginning, the main question is how do I attach it to the username mid string?
The API returns the username and i've added that to a variable here:
var userToHighlight = json[i].participants[1].username;
Any ideas how this can be achieved?
Simon
Injecting a username into a string isn't that hard when using String.format()
. A good tutorial can be found on TiDev .
Basically:
var message = String.format('Welcome, %s! You are visitor number %d', forename, number);
In your case, make the original text with variables, and inject them later.
var text = "You are now friends with @%s";
var text = "@%s likes your post";
Then in attributed string:
text: String.format(text, userToHighlight)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.