标签: nsmutableattributedstring

使用Swift在UITextField中使用不可编辑的前缀

我在UITextField使用新Swift语言创建前缀时遇到了问题.目前我已经创建了UITextField使用Interface Builder并且已经分配了一个IBOutlet名为usernameFieldtextFieldDidBeginEditing函数,然后使用我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)

uitextfield nsmutableattributedstring swift

3
推荐指数
2
解决办法
3831
查看次数

替换 NSMutableAttributedString 中的字符

这适用于常规NSString

NSString *newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];
Run Code Online (Sandbox Code Playgroud)

但是没有这样的方法NSMutableAttributedString。如何删除 中逗号的所有实例NSMutableAttributedString

nsstring ios nsmutableattributedstring

3
推荐指数
1
解决办法
5055
查看次数

将 2 行属性字符串添加到 UIButton 的标题不起作用

我有一个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 行。

uibutton ios nsmutableattributedstring swift

3
推荐指数
1
解决办法
846
查看次数

创建具有静态和属性前缀的UITextField

我想做一个UITextField,它有一个静态前缀,用户不能编辑或删除,同时也用浅灰色字体颜色.

文本字段的可编辑部分应始终以黑色显示.

下面给出一个例子:

在此输入图像描述

它主要用于输入用户名,带有不断添加前缀的域.


我已经尝试过使用textFieldShouldCleartextField: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)

uitextfield ios nsmutableattributedstring

2
推荐指数
1
解决办法
3378
查看次数

iOS 7.0.3中的NSMutableAttributedString崩溃

几天之后,我发生了一次崩溃,只发生在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中运行得非常好)

ios nsmutableattributedstring ios7

2
推荐指数
1
解决办法
4610
查看次数

将目标字符串中的正则表达式匹配替换为Objective-C中的图像

我的目标是在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)

目前这种方法存在两个问题:

  • 大括号不会被替换,只会替换它们内部的文本.
  • 每个匹配的范围都在变化,因为字符串本身正在发生变化,并且每个替换的原始文本长度> 1时,它会变得更多.这是它的样子:

图片http://i57.tinypic.com/idgeqh.png

objective-c nsattributedstring nsregularexpression nsmutableattributedstring

2
推荐指数
1
解决办法
1663
查看次数

具有右对齐的NSAttributedString在末尾删除空格

我创建了一个简单的聊天应用程序,其中我们的消息在右侧(右对齐),所有其他消息在左侧(左对齐).我正在使用,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

2
推荐指数
1
解决办法
1767
查看次数

iOS10.3系统富文本删除线无法显示

Apple最近发布的iOS 10.3版本,使用前NSMutableAttributedString设置的前锋不显示

    [attributedString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle | NSUnderlinePatternSolid) range:NSMakeRange(length1 + 7, length2 + 5)];
Run Code Online (Sandbox Code Playgroud)

尝试了很多方法都没有解决,希望能得到大家的帮助

ios nsmutableattributedstring ios10.3

2
推荐指数
1
解决办法
639
查看次数

如何更改属性字符串中字符的对齐方式

这就是我想要实现的目标。

在此输入图像描述

我使用了一个,获取字符$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)

但结果是

在此输入图像描述

如何从下到上更改该特定字符的对齐方式?

ios nsmutableattributedstring swift

2
推荐指数
1
解决办法
3554
查看次数

Swift - 检查属性文本是否为空

我有一个 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 执行相同的检查?

string nsattributedstring nsmutableattributedstring swift

2
推荐指数
1
解决办法
749
查看次数

如何更改标签中某些单词的颜色-Swift 3

用简单的文本创建了一个标签。

如何更改标签中某些单词的颜色?

迅捷3

像下面一样

预期结果

label colors nsmutableattributedstring swift swift3

1
推荐指数
1
解决办法
2848
查看次数

带换行符 (\n) 的 AttributedString 无法正常工作

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)

在此输入图像描述

nsattributedstring ios nsmutableattributedstring swift3

1
推荐指数
1
解决办法
4450
查看次数

突出显示或下划线字符串中的特定单词

我想强调或强调一个特定的单词集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)

此代码更接近正确的路径.我确实看到一个突出显示的字符,但它是字符串中的第一个字符,而不是我搜索过的字符.

objective-c ios nsmutableattributedstring

0
推荐指数
1
解决办法
2584
查看次数