【问题标题】:SWIFT: How to refresh textview from array when button pressed?SWIFT:按下按钮时如何从数组中刷新文本视图?
【发布时间】:2015-02-17 12:12:20
【问题描述】:

我有一个包含多个字符串的数组,而 textView 只显示其中一个字符串(这已经很完美了)。但是现在我想在按下按钮时刷新文本视图。但它不起作用。我尝试过但没有用的方法:

@IBAction func refreshButtonDidPress(sender: AnyObject) {
randomizedText()
}

randomizedText() 是一个函数,我只是在其中加载我的随机字符串数组。而且我在 viewDidLoad 中调用了这个函数,所以开始时的 textView 不为空。

希望你能帮忙。

更新完整代码:

函数随机文本():

func randomizedText() {
    textView.text = randomIdioms
    textView.selectable = false
}

randomIdioms 来自以下单独的扩展:

extension Int {
    public static func randomIn(#range: Range<Int>) -> Int {
        let difference = range.endIndex - range.startIndex
        let randomPick = arc4random_uniform(UInt32(difference))
        return Int(randomPick) + range.startIndex
    }
}

let idioms = [
    "One Two Test",
    "This is the second exampleThis is the second example",
    "The last exampleThe last exampleThe last exampleThe last example"
]
let randomIdioms = idioms[Int.randomIn(range: 0..<idioms.count)]

按照建议,现在我尝试了:

@IBAction func refreshButtonDidPress(sender: AnyObject) {
randomizedText()
textView.setNeedsDisplay()
}

但这不起作用。我可以多次按下刷新按钮,而无需使用另一个字符串重新刷新 textView。

下一次更新,随机工作: 我没有在扩展中使用随机生成,而是在我的 func 中尝试了这个并在@IBAction fun refreshButtonDidPress 中调用它并且它可以工作:

func randomizedText() {
    let idioms = ["One Two Test", "This is the second exampleThis is   the second example", "I am not the idiom", "The last exampleThe last exampleThe last exampleThe last example"]
    let index = Int(arc4random_uniform(UInt32(idioms.count)))
    textView.text = idioms[index]
    textView.selectable = false
}

但我没有胶水扩展程序出了什么问题。

【问题讨论】:

  • 除非我们看到 randomizeText 是做什么的,否则我们将无法提供帮助。
  • 是的,在这里发布函数的代码
  • 我已经用完整的代码更新了我的初始帖子,也没有成功调用 textView.setNeedsDisplay()。

标签: arrays swift uitextview


【解决方案1】:

您必须将UITextViewtext 属性分配给您要显示的字符串。 UITextView 不会保留对数组中您给它的字符串的引用。它复制它。 UITextView 将处理它自己的绘制调用以及何时需要重绘。

【讨论】:

  • 在这里我有点挣扎如何处理这个问题。我是否必须在 refreshButtonDidPress 函数和 textView.setneedsdisplay() 中写入 textView.text = randomText?
  • 听起来不错。我不确定您是否甚至需要调用 setNeedsDisplay() 因为更改文本显然需要更新视图,因此它可以自行调用它。试试看。
【解决方案2】:

您需要向文本视图发送setNeedsDisplay() 消息。您可以在您的 randomizedText() 函数中执行此操作,或者在您调用 randomizedText() 后在 refreshButtonDidPress() 中执行此操作。

在调用 setNeedsDisplay() 之前,您还需要在 textView 上设置 textattributedText 属性

【讨论】:

  • 嗨,马克,我都试过了,但没有任何反应(不是重新加载另一个字符串):@IBAction func refreshButtonDidPress(sender: AnyObject) { randomText() textView.setNeedsDisplay() }
猜你喜欢
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 2020-08-28
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多