'下标'不可用:不能使用Int下标String,请参阅文档注释以供讨论

时间:2017-01-30 10:18:09

标签: ios swift

ScreenShot of issue

我想从单元格中更改所选String的颜色。 下面给出了一些代码块来帮助我。

'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

{
    let Cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath)as! FirstTableViewCell
    Cell.selectionStyle = .none

    Cell.marqueeLabel1.type = .continuous
    Cell.marqueeLabel1.animationCurve = .easeInOut

    let strings = "Purchase bids- 0123456789     Sell Bids- 0123456789     Cleared- 0123456789     "

    let txtfield1 :UITextField!

    let string_to_color = "0123456789"

    let range = (strings as NSString).range(of: string_to_color)

    let attribute = NSMutableAttributedString.init(string: strings)
    attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range)

    txtfield1 = UITextField.init(frame:CGRect(x:10 , y:20 ,width:100 , height:100))
    txtfield1.attributedText = attribute

    Cell.marqueeLabel1.text = strings[Int(arc4random_uniform(UInt32(strings.count)))]
    Cell.marqueeLabel2.type = .continuous
    Cell.marqueeLabel2.animationCurve = .easeInOut
    let strings2 = ["Purchase bids- 0123456789     Sell Bids- 0123456789     Cleared- 0123456789     "]

    // Cell.marqueeLabel2.text = strings[Int(arc4random_uniform(UInt32(strings2.count)))]

    return Cell
}

2 个答案:

答案 0 :(得分:0)

try! 不像你的字符串数组 等,

let array = ["Frodo", "sam", "wise", "gamgee"]
 Cell.marqueeLabel1.text = array [Int(arc4random_uniform(UInt32(array.count)))]

答案 1 :(得分:0)

这是有效的(您需要使用doc:https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID494中的下标方法):

let strings = " 1234 1234 4567"
let myString = strings[strings.index(strings.startIndex, offsetBy: String.IndexDistance(arc4random_uniform(UInt32(strings.characters.count))))]