菜鸟教程小白 发表于 2022-12-11 18:20:55

ios - 如何在 Swift 中将枚举和 switch() 与 UITableViewController 一起使用


                                            <p><p>我的 UITableView 有两个部分,所以我为它们创建了一个枚举:</p>

<pre><code>private enum TableSections {
    HorizontalSection,
    VerticalSection
}
</code></pre>

<p>如何使用 numberOfRowsInSection 委托(delegate)方法中传递的“section”变量进行切换?看来我需要将“部分”转换为我的枚举类型?或者有没有更好的方法来做到这一点?</p>

<p>错误是<strong>“Enum case "Horizo​​ntalSection"not found in type 'int'.</strong></p>

<pre><code>override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {

    switch section {

    case .HorizontalSection:
      return firstArray.count

    case .VerticalSection:
      return secondArray.count

    default
      return 0
    }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>为了做到这一点,你需要给你的枚举一个类型(在这种情况下是 Int):</p>

<pre><code>private enum TableSection: Int {
    horizontalSection,
    verticalSection
}
</code></pre>

<p>这使得“horizo​​ntalSection”将被赋值为 0,而“verticalSection”将被赋值为 1。</p>

<p>现在在您的 <code>numberOfRowsInSection</code> 方法中,您需要在枚举属性上使用 <code>.rawValue</code> 以访问它们的整数值:</p>

<pre><code>override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {

    switch section {

    case TableSection.horizontalSection.rawValue:
      return firstArray.count

    case TableSection.verticalSection.rawValue:
      return secondArray.count

    default:
      return 0
    }
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在 Swift 中将枚举和 switch() 与 UITableViewController 一起使用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41214988/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41214988/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在 Swift 中将枚举和 switch() 与 UITableViewController 一起使用