[英]Attributed strings in Appcelerator and applying the @ symbol mid string
I'm struggling a little bit with attributed strings in Appcelerator and was hoping for some assistance. 我在Appcelerator中使用属性字符串有点挣扎,希望能提供一些帮助。
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. 我使用API来检索用户信息,但是应用程序需要在该用户名前显示@,并使用与其余字符串不同的颜色。 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... 方案1可以,但是方案2当前看起来像这样...
@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: API返回用户名,我将其添加到此处的变量中:
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()
. 使用String.format()
时,将用户名注入字符串并不难。 A good tutorial can be found on TiDev . 在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.