【问题标题】:add a button to a programmatically created uitableview cell将按钮添加到以编程方式创建的 uitableview 单元格
【发布时间】:2020-10-16 15:35:50
【问题描述】:

我希望我的 swift 代码在第一个 tableview 单元格中放置一个按钮。我的代码使用所有代码,没有情节提要。我不知道在 2 tableview funcs 数据源和委托中放置什么。该按钮不应触发任何操作,该按钮应位于第一个单元格中。

import UIKit

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        <#code#>
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        <#code#>
    }
    

    
    
   
    var tble = UITableView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        [tble].forEach{
            view.addSubview($0)
            $0.translatesAutoresizingMaskIntoConstraints = false
            
        }
        tble.dataSource = self
        tble.delegate = self
        tble.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
        NSLayoutConstraint.activate([
            
           
            
            tble.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            tble.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tble.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier:  0.8),
            tble.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier:  1),
            
            
        ])
  
     
    }
    
 
    
    
}

【问题讨论】:

    标签: swift uitableview button delegates


    【解决方案1】:

    1- 从 UITableViewCell 创建类 2-将单元格注册到tableView 3-在tableviewcellforrow函数中使用带有标识符的tableView dequeue作为索引

    【讨论】:

      【解决方案2】:
      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
      
          if(indexPath.row == 0) {
              let cellButton = UIButton(frame: CGRect(x: 5, y: 5, width: 50, height: 30))
              cell.addSubview(cellButton)
              # put other logic
          }
          else {
              # put other logic
          }
          
          return cell
      }
      

      希望对你有所帮助。不好意思,XCode里我其实没查,不过是骨架。

      【讨论】:

        猜你喜欢
        • 2020-10-18
        • 1970-01-01
        • 1970-01-01
        • 2020-05-06
        • 2015-04-10
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多