【问题标题】:Programmatically change attributed title of UIButton以编程方式更改 UIButton 的属性标题
【发布时间】:2014-11-07 10:33:54
【问题描述】:

我想以编程方式更改具有属性标题的UIButton 的标题。 该按钮是在 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];

谢谢!

【问题讨论】:

    标签: ios uibutton


    【解决方案1】:

    部分你有答案。

     NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[_ deleteButton attributedTitleForState:UIControlStateNormal]];
    
    [attributedString replaceCharactersInRange:NSMakeRange(0, attributedString.length) withString:@"Your new string"];
    
    [_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 
    

    而不是创建NSAttributedString 创建NSMutableAttributedString 然后你可以像这样设置字符串。

    【讨论】:

      【解决方案2】:

      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)
      }
      

      【讨论】:

        【解决方案3】:

        这真的取决于你的属性字符串:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-21
          • 2014-08-22
          • 1970-01-01
          • 2015-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-27
          相关资源
          最近更新 更多