我在UITextField使用新Swift语言创建前缀时遇到了问题.目前我已经创建了UITextField使用Interface Builder并且已经分配了一个IBOutlet名为usernameField的textFieldDidBeginEditing函数,然后使用我NSMutableAttributedString在其中编写的函数,名为usernamePrefix,仅包含单词"C-TAD-",最后我限制了UITextField最大字符数字为13,如下:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var usernameField : UITextField!
private var usernamePrefix = NSMutableAttributedString(string: "C-TAD-")
func textFieldDidBeginEditing(textField: UITextField) {
if textField == usernameField {
if usernameField.text == "" {
usernameField.attributedText = usernamePrefix
}
}
usernameField.addTarget(self, action: "textFieldDidChangeText:", forControlEvents:UIControlEvents.EditingChanged)
}
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
let maxUsernameLength = countElements(usernameField.text!) + countElements(string!) - range.length …Run Code Online (Sandbox Code Playgroud) 这适用于常规NSString:
NSString *newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];
Run Code Online (Sandbox Code Playgroud)
但是没有这样的方法NSMutableAttributedString。如何删除 中逗号的所有实例NSMutableAttributedString?
我有一个UIButton. 我试图让buttons title2 行,第二行应该比第一行小。这是我的代码:
var myMutable = NSMutableAttributedString(string: "someText\n\(someString)", attributes: [NSFontAttributeName:UIFont.systemFontOfSize(17)])
myMutable.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: NSRange(location: count("someText\n") - 1, length: count(someString) - 1))
self.myButton.setAttributedTitle(myMutable, forState: .Normal)
Run Code Online (Sandbox Code Playgroud)
出于某种原因,当这段代码被执行时,什么也没有发生。我做错了什么,我该如何解决?
更新
我只是尝试为它添加颜色,这部分起作用了。所以唯一的事情是,它没有 2 行。
我想做一个UITextField,它有一个静态前缀,用户不能编辑或删除,同时也用浅灰色字体颜色.
文本字段的可编辑部分应始终以黑色显示.
下面给出一个例子:

它主要用于输入用户名,带有不断添加前缀的域.
我已经尝试过使用textFieldShouldClear和textField:shouldChangeCharactersInRange:replacementString:委托方法NSMutableAttributedString,但是根本无法解决它:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSMutableAttributedString *text = [textField.attributedText mutableCopy];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 7)];
if (textField.text.length > 7)
{
[text addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(7, textField.attributedText.length - 7)];
}
[text addAttribute:NSFontAttributeName value:[UIFont gothamFontForSize:textField.font.pointSize andWeight:kGothamLight] range:NSMakeRange(0, textField.attributedText.length)];
return range.location > 6;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"kombit\\"];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 7)];
[text addAttribute:NSFontAttributeName value:[UIFont gothamFontForSize:textField.font.pointSize andWeight:kGothamLight] …Run Code Online (Sandbox Code Playgroud) 几天之后,我发生了一次崩溃,只发生在iOS中,代码如下
[myAttributedString addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"HelveticaNeue-Italic" size:myLabel.font.pointSize]
range:rangeOfSubString];
Run Code Online (Sandbox Code Playgroud)
调试器给出的原因是
"由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'NSConcreteMutableAttributedString addAttribute:value:range :: nil value'"Exception Type:SIGABRT
我从文档中知道它的价值是零.知道为什么[UIFont fontWithName:@"HelveticaNeue-Italic"size:myLabel.font.pointSize]会在iOS 7.0.3中返回nil吗?(它在iOS 7.0.2中运行得非常好)
我的目标是在Parse.com中存储属性字符串的信息.我决定为我的图像提供一个属性文本的编码,通过用{X}相应的图像替换大括号中的任何字符串来工作.例如:
Picture of 2 colorless mana: {X}
Run Code Online (Sandbox Code Playgroud)
应该生成一个{X}由图像替换的属性字符串.这就是我尝试过的:
NSString *formattedText = @"This will cost {2}{PW}{PW} to cast.";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\{)[^}]+(?=\\})" options:NSRegularExpressionAnchorsMatchLines
error:nil];
NSArray *matches = [regex matchesInString:formattedText
options:kNilOptions
range:NSMakeRange(0, formattedText.length)];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formattedText];
for (NSTextCheckingResult *result in matches)
{
NSString *match = [formattedText substringWithRange:result.range];
NSTextAttachment *imageAttachment = [NSTextAttachment new];
imageAttachment.image = [UIImage imageNamed:[NSString stringWithFormat:@"Mana%@.png", match]];
NSAttributedString *replacementForTemplate = [NSAttributedString attributedStringWithAttachment:imageAttachment];
[attributedString replaceCharactersInRange:result.range
withAttributedString:replacementForTemplate];
}
[_textView setAttributedText:attributedString];
Run Code Online (Sandbox Code Playgroud)
目前这种方法存在两个问题:
objective-c nsattributedstring nsregularexpression nsmutableattributedstring
我创建了一个简单的聊天应用程序,其中我们的消息在右侧(右对齐),所有其他消息在左侧(左对齐).我正在使用,NSAttributedString因为我大量修改文本的颜色等.每条消息都是UILabel.我的问题是,在正确对齐的消息的末尾,我想放一个空格,所以它看起来像这样:
"Some example sentence "
Run Code Online (Sandbox Code Playgroud)
而不是这样的:
"Some example sentece"
Run Code Online (Sandbox Code Playgroud)
每次我把空白放在那里它都被删除了(我也尝试了不间断的空间\u00a0,我得到了同样的问题(空格被删除)我的右对齐代码如下所示:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.text /*attributes:attrDict*/];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentRight];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];
Run Code Online (Sandbox Code Playgroud)
后来我添加了一些其他属性与颜色等(没有任何改变文本本身).文本总是像最后一样用最后的空格:"Some example sentece "
最后我做这样的事情:
self.attributedText = attributedString;
Run Code Online (Sandbox Code Playgroud)
并且...我的空间被删除了.如何防止我的文本删除最后的空格?我需要那里.
编辑:
if (self.textAlignment == NSTextAlignmentRight) {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentRight];
[paragraphStyle setTailIndent:0.1];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];
}
Run Code Online (Sandbox Code Playgroud)
这是我的tailIndent代码,它看起来像这样.在tailIndent之前,我在聊天的右侧有一条消息"test"(这里是左边因为我不知道如何正确对齐文本:P):
测试
在tailIndent之后:
Ť
那么会发生什么:文本从右到左,在这种情况下只留下最后一个字符.只有tailIndent 0.1!
whitespace objective-c nsattributedstring right-align nsmutableattributedstring
Apple最近发布的iOS 10.3版本,使用前NSMutableAttributedString设置的前锋不显示
[attributedString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle | NSUnderlinePatternSolid) range:NSMakeRange(length1 + 7, length2 + 5)];
Run Code Online (Sandbox Code Playgroud)
尝试了很多方法都没有解决,希望能得到大家的帮助
这就是我想要实现的目标。
我使用了一个,获取字符$attributedString的范围并对其应用属性,如下所示:
let str = "$4"
let r1 = str.range(of: "$")!
let n1 = NSRange(r1, in: str)
let atrStr = NSMutableAttributedString(string: str)
atrStr.addAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 25)], range: n1)
atrStr.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.lightGray], range: n1)
lbl.attributedText = atrStr
Run Code Online (Sandbox Code Playgroud)
但结果是
如何从下到上更改该特定字符的对齐方式?
我有一个 UITextField,我将当前值设置为属性文本,如下所示:
public var currentValue: NSAttributedString {
get {
return inputField.attributedText ?? NSAttributedString()
}
set {
inputField.attributedText = newValue
}
}
Run Code Online (Sandbox Code Playgroud)
这以前只是一个字符串,但我现在需要为部分文本添加格式。
但是,我有一种方法需要传递这些字段,该方法以查看该字段是否为空的条件开头。以前我是这样开始的:
if textField.currentValue.isEmpty {
// Perform logic
}
Run Code Online (Sandbox Code Playgroud)
然而,显然 NSAttributedText 没有 isEmpty 成员。如何对 NSAttributedText 执行相同的检查?
用简单的文本创建了一个标签。
如何更改标签中某些单词的颜色?
迅捷3
像下面一样

Continue reading我在最后添加。如果文本中有任何换行符,则无法继续阅读。这是 iOS 特有的错误还是我遗漏了什么?
let activityData.feed = "Hi this is \n \n stack overflow"
let formattedString = NSMutableAttributedString()
formattedString.normal(activityData.feed!).bold(LanguageManager.shared.getLocale(key: "Continue Reading"))
labelFeed.attributedText = formattedString
Run Code Online (Sandbox Code Playgroud)
属性字符串的扩展
extension NSMutableAttributedString {
@discardableResult func bold(_ text:String) -> NSMutableAttributedString {
let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont.systemFont(ofSize: 16.0), NSForegroundColorAttributeName : UIColor.CNS_BlueColor]
let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
self.append(boldString)
return self
}
@discardableResult func normal(_ text:String)->NSMutableAttributedString {
let normal = NSAttributedString(string: text)
self.append(normal)
return self
}
}
Run Code Online (Sandbox Code Playgroud)
我想强调或强调一个特定的单词集NSString.我能够检测到这些单词是否存在,我只是无法突出显示它们.
NSString * wordString = [NSString stringWithFormat:@"%@", [self.myArray componentsJoinedByString:@"\n"]];
self.myLabel.text = wordString;
if ([wordString rangeOfString:@"Base Mix"].location == NSNotFound)
{
NSLog(@"string does not contain base mix");
}
else
{
NSLog(@"string contains base mix!");
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:wordString];
NSString * editedString = [NSString stringWithFormat:@"%lu", (unsigned long)[wordString rangeOfString:@"Base Mix"].location];
NSRange theRange = NSMakeRange(0, [editedString length]);
[string beginEditing];
[string removeAttribute:NSForegroundColorAttributeName range:theRange];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:theRange];
[string endEditing];
[self.myLabel setAttributedText:string];
}
Run Code Online (Sandbox Code Playgroud)
此代码更接近正确的路径.我确实看到一个突出显示的字符,但它是字符串中的第一个字符,而不是我搜索过的字符.
ios ×8
swift ×5
objective-c ×3
swift3 ×2
uitextfield ×2
colors ×1
ios10.3 ×1
ios7 ×1
label ×1
nsstring ×1
right-align ×1
string ×1
uibutton ×1
whitespace ×1