【问题标题】:How to go through array with button press如何通过按钮按下阵列
【发布时间】:2020-08-15 13:49:55
【问题描述】:

我有一个包含不同信息的数组,

如何通过按下按钮来遍历数组?我有两个按钮,我需要允许一个在数组中向前移动,并允许后退按钮显示上一个索引。


  @IBOutlet weak var backButton: UIButton!
  @IBOutlet weak var nextButton: UIButton!



 @IBOutlet weak var infoLabel: UILabel!
 @IBOutlet weak var pageControl: UIPageControl!



Let infoArray = ["info1","info2","info3","info4"] 

@IBAction func nextTapped(_ sender: Any) {
// Change the label based on the selected index in array        

}

@IBAction func backTapped(_ sender: Any) {
 //Return to previous index and update label text

}

我还添加了页面控件以获得更好的用户体验,但现在我只是担心学习如何通过按钮 Tap 更改标签。

我的猜测是从 0 开始索引,即 info1 并从那里开始。我可以担心以后保存索引状态。

非常感谢任何帮助。

【问题讨论】:

  • “我的猜测是从 0 开始索引,这将是 info1 并从”开始,这是正确的。

标签: ios arrays swift uibutton uilabel


【解决方案1】:

逻辑应该是这样的

let infoArray = ["info1","info2","info3","info4"]

func viewDidLoad() {
    pageControl.numberOfPages = infoArray.count
    pageControl.currentPage = 0
}

@IBAction func nextTapped(_ sender: Any) {
    // Change the label based on the selected index in array
    guard pageControl.currentPage + 1 < infoArray.count else {
        return
    }
    pageControl.currentPage += 1
}

@IBAction func backTapped(_ sender: Any) {
    //Return to previous index and update label text
    guard pageControl.currentPage - 1 >= 0 else {
        return
    }
    pageControl.currentPage -= 1
}

当用户点击页面控件以移动到下一页或上一页时,该控件会发送 valueChanged 事件以供委托处理。然后,委托可以评估 currentPage 属性以确定要显示的页面。页面控件在任一方向仅前进一页。

【讨论】:

  • 很好的答案 我可以在函数中实现页面控制。感谢您的回复,会竖起大拇指的!
【解决方案2】:

请检查下面的代码,您可以执行类似的操作来前后移动阵列。请根据需要添加其他检查。

var i = 0
let infoArray = ["info1","info2","info3","info4"]

@IBAction func nextTapped(_ sender: Any) {
    // Change the label based on the selected index in array
   if i >= 0 && i < infoArray.count{
   dataLbl.text = infoArray[i]

    }
    if i > 3 {
        i = i-1
    } else  {
        i = i+1
    }

}

@IBAction func backTapped(_ sender: Any) {
    //Return to previous index and update label text
    if i >= 0 && i < infoArray.count-1 {
    dataLbl.text = infoArray[i]

    }
    if i < 0 {
        i = i+1
    } else  {
       i = i-1
    }

}

【讨论】:

  • 虽然我可以遍历数组,但这段代码的问题是,一旦你到达最终索引,它就不允许我返回到前一个索引。
  • 这个答案与我的问题最相关,我会从这里找出其余的,所以我会接受,谢谢。
猜你喜欢
  • 2016-07-09
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 2011-09-14
  • 2021-06-08
相关资源
最近更新 更多