Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 以编程方式更改UIButton的属性化标题_Ios_Uibutton - Fatal编程技术网

Ios 以编程方式更改UIButton的属性化标题

Ios 以编程方式更改UIButton的属性化标题,ios,uibutton,Ios,Uibutton,我想以编程方式更改具有属性标题的ui按钮的标题。 按钮是在IB中创建的。我不想更改属性,只想更改标题/文本 我尝试了下面的代码,但找不到更改NSAttributedString标题的方法 NSAttributedString *attributedString = [self.deleteButton attributedTitleForState:UIControlStateNormal]; // How can I change title of attributedString with

我想以编程方式更改具有属性标题的
ui按钮的标题。
按钮是在IB中创建的。我不想更改属性,只想更改标题/文本

我尝试了下面的代码,但找不到更改
NSAttributedString
标题的方法

NSAttributedString *attributedString = [self.deleteButton attributedTitleForState:UIControlStateNormal];

// How can I change title of attributedString without changing the attributes?

[self.deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal];

谢谢大家!

你有一部分答案

 NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[_ deleteButton attributedTitleForState:UIControlStateNormal]];

[attributedString replaceCharactersInRange:NSMakeRange(0, attributedString.length) withString:@"Your new string"];

[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 

不必创建
NSAttributedString
create
NSMutableAttributedString
,您可以这样设置字符串。

这实际上取决于您的attributedString:

  • “普通”属性字符串: 这意味着您的attrString只有一组适用于整个字符串长度的属性。在这种情况下,您可以执行以下操作:

    NSAttributedString *attrString = WHATEVER;
    NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL];
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER
                                                                        attributes:attributes];
    
  • attributedString具有不同的属性范围:
    这可能会变得非常复杂,具体取决于attributedString的结构,因为您需要进行大量的范围处理等。在这种情况下,最好创建一个新的
    NSMutableAttributedString
    并从头开始设置属性


  • Swift 3回答:

    if let attributedTitle = yourButton.attributedTitle(for: .normal) {
        let mutableAttributedTitle = NSMutableAttributedString(attributedString: attributedTitle)
        mutableAttributedTitle.replaceCharacters(in: NSMakeRange(0, mutableAttributedTitle.length), with: "New title")
        yourButton.setAttributedTitle(mutableAttributedTitle, for: .normal)
    }
    

    可以担保,仍然在Swift 5中工作。