【问题标题】:how to change int value on label text every time when button click每次单击按钮时如何更改标签文本上的int值
【发布时间】:2019-03-24 19:18:07
【问题描述】:

//这是我在字符串中也使用颜色标签的代码

var cellIndex: Int = 0
override func viewDidLoad() {
    super.viewDidLoad()
    cellIndex = 1
    let s1 = "word \(cellIndex) to \(cellIndex+7)"
    let mystring:NSString = "\(s1) recovery phrases" as NSString
    var myMutableString = NSMutableAttributedString()
    myMutableString =  NSMutableAttributedString(string:mystring as String, attributes: [NSAttributedString.Key.font:Font.mediumRegularFont()])
    myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: Color.darkColor(), range: NSRange(location:0,length:s1.count))
    stepBarView.attributedText = myMutableString
}
@IBAction func onNextButtonTap(_ sender: Any) {
    // i want to change cellIndex Value every time when i press button.
}

【问题讨论】:

    标签: ios swift xcode swift4


    【解决方案1】:

    你有两个选择

    1 用 replacingOccurrences 替换该值,但需要考虑该数字可能有多少位数。 2 再次重新创建整个字符串,这样更快,工作更少

    【讨论】:

      【解决方案2】:

      您可以在 cellIndex 中使用 didSet。

      var cellIndex: Int = 0 {
          didSet {
              let s1 = "word \(cellIndex) to \(cellIndex+7)"
              let mystring:NSString = "\(s1) recovery phrases" as NSString
              var myMutableString = NSMutableAttributedString()
              myMutableString =  NSMutableAttributedString(string:mystring as String, attributes: [NSAttributedString.Key.font:Font.mediumRegularFont()])
             myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: Color.darkColor(), range: NSRange(location:0,length:s1.count))
              stepBarView.attributedText = myMutableString
          }
      } 
      

      现在,只要将 value 设置为 cellIndex,它就会使用所需的字符串更新标签。

      【讨论】:

      • 你能告诉我 didset 的具体功能是什么吗?
      • 变量赋值后调用。
      • 很好的解决方案 .. (y)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多