class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var countryNames:[String]!
var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.countryNames = ["中国🇨🇳","美国🇺🇸","日本🇯🇵","德国🇩🇪","俄罗斯🇷🇺"]
self.tableView = UITableView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height), style: .grouped)
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
let headView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: 50.0))
headView.backgroundColor = UIColor.red
self.tableView.tableHeaderView = headView
}
// UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int
{
return 4
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.countryNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let CellIdentifier = "SwiftCell"
var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: CellIdentifier)
}
cell!.accessoryType = .disclosureIndicator
cell?.textLabel?.text = self.countryNames[indexPath.row]
return cell!
}
// UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
let country = self.countryNames[indexPath.row]
NSLog("选择\(country)")
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
return 100.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: 100.0))
view.backgroundColor = UIColor.blue
return view
}
}
网友评论