swift-UITableView的基本使用,swift-uitableview
廢話不多說了,直接貼我今天寫的代碼吧:如果新手有什麼不懂的,可以發我郵箱。
//
// singleInfo.swift 個人資訊
// Housekeeper
//
// Created by 盧洋 on 15/10/27.
// Copyright © 2015年 奈文摩爾. All rights reserved.
//
import Foundation
import UIKit
class singleInfo:UIViewController,UITableViewDataSource,UITableViewDelegate{
var dataTable:UITableView!; //資料表格
var itemString=["暱稱","帳號","性別","地區","我的愛車"]
//當前螢幕對象
var screenObject=UIScreen.mainScreen().bounds;
//頁面初始化
override func viewDidLoad() {
super.viewDidLoad();
initView();
}
/**
UI 初始化
*/
func initView(){
self.title="我的資料";
self.view.backgroundColor=UIColor.linghtGreyBg();
creatTable();
}
/**
我的資料表格初始化
*/
func creatTable(){
let dataTableW:CGFloat=screenObject.width;
let dataTableH:CGFloat=screenObject.height;
let dataTableX:CGFloat=0;
let dataTableY:CGFloat=0;
dataTable=UITableView(frame: CGRectMake(dataTableX, dataTableY, dataTableW, dataTableH),style:UITableViewStyle.Grouped);
dataTable.delegate=self; //實現代理
dataTable.dataSource=self; //實現資料來源
self.view.addSubview(dataTable);
}
//1.1預設返回一組
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2;
}
// 1.2 返回行數
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(section == 0){
return 1;
}else{
return 5;
}
}
//1.3 返回行高
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
if(indexPath.section == 0){
return 80;
}else{
return 55;
}
}
//1.4每組的頭部高度
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10;
}
//1.5每組的底部高度
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1;
}
//1.6 返回資料來源
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier="identtifier";
var cell=tableView.dequeueReusableCellWithIdentifier(identifier);
if(cell == nil){
cell=UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier);
}
if(indexPath.section == 0){
cell?.textLabel?.text="頭像";
}else{
cell?.textLabel?.text=itemString[indexPath.row];
}
cell?.accessoryType=UITableViewCellAccessoryType.DisclosureIndicator;
return cell!;
}
//1.7 表格點擊事件
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//取消選中的樣式
tableView.deselectRowAtIndexPath(indexPath, animated: true);
//擷取點擊的行索引
if(indexPath.row == 0){
let pushSingleInfo=singleInfo();
pushSingleInfo.hidesBottomBarWhenPushed=true; //隱藏導覽列
self.navigationController?.pushViewController(pushSingleInfo, animated: true);
}
}
//記憶體警告
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
print("個人資訊記憶體警告");
}
}
如下: