用Swift语言 来写表格

来源:互联网 发布:广发淘宝卡新规则 编辑:程序博客网 时间:2024/06/09 20:05

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

这里写图片描述

//在AppDelegate 文件中UIViewController,UITableViewDataSource,UITableViewDelegate {    var datas:Array<News>?    var tableView:UITableView?    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {        let onenNews = self.datas?[indexPath.row]        let detailVC = DetailViewController()        detailVC.detailURL = onenNews?.weburl        self.navigationController?.pushViewController(detailVC, animated: true)    }    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        if let count = datas?.count {            return count        }        return 0    }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        let str = "identifier"        var cell = tableView.dequeueReusableCell(withIdentifier: str)        if cell == nil {            cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: str)        }//        let newsDic = self.datas?[indexPath.row] as!//        Dictionary<String,String>//        //        cell?.textLabel?.text = newsDic["title"]//        //        cell?.detailTextLabel?.text = newsDic["time"]        let oneNew = self.datas![indexPath.row]        cell?.textLabel?.text = oneNew.title        cell?.detailTextLabel?.text = oneNew.time        return cell!    }    override func viewWillAppear(_ animated: Bool) {        self.getURLDatas()    }    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view.        tableView = UITableView.init(frame: self.view.frame, style: UITableViewStyle.plain)        tableView?.dataSource = self        tableView?.delegate = self        self.view.addSubview(tableView!)    }    func getURLDatas() -> Void {        let appkey = "de394933e1a3e2db"        let urlStr = "http://api.jisuapi.com/news/get?channel=头条&start=0&num=20&appkey=\(appkey)"//        let urlString = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "`#%^{}\"[]|\\<> ").inverted)        let url = URL(string:urlStr.addingPercentEscapes(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!)        print(url)        let request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 15.0)        let session = URLSession.shared        let task = session.dataTask(with: request) { (data, response, error) in            if error != nil {                print("错误")                return            }            let obj = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as!                Dictionary<String,Any>            print(obj)            let result = obj["result"] as! Dictionary<String,Any>            let list = result["list"] as! Array<Any>            var newsArr:[News]? = []            for item in list {                let newsDic = item as!                    Dictionary<String,String>                let oneNew = News()                oneNew.title = newsDic["title"]                oneNew.time = newsDic["time"]                oneNew.url = newsDic["url"]                oneNew.weburl = newsDic["weburl"]                newsArr?.append(oneNew)            }            self.datas = newsArr            //回到Ui主线程刷新表格            DispatchQueue.main.async(execute: {                 self.tableView?.reloadData()            })        }        task.resume()    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }**## 标题 ##//在StudentsViewController 文件中-----------------------------**UIViewController,UITableViewDataSource {    var studentsData:[String]?    override func viewDidLoad() {        super.viewDidLoad()        studentsData = ["大川","建军","光辉","枕头"]        let table = UITableView.init(frame: self.view.frame, style: UITableViewStyle.plain)        table.dataSource = self        self.view.addSubview(table)        // Do any additional setup after loading the view.    }    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        if let count = self.studentsData?.count {            return count        }        return 0    }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        let str = "identifier"        var cell = tableView.dequeueReusableCell(withIdentifier: str)        if cell == nil {            cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: str)        }        cell?.textLabel?.text = self.studentsData?[indexPath.row]        return cell!    }**## 标题 ##//在MyUIViewController 文件中-----------------------------**UIViewController,UITextFieldDelegate {    var myLable:UILabel = UILabel.init(frame: CGRect(x: 30, y: 80, width: 100, height: 30))    var myBtn:UIButton?    var textFiled:UITextField?    var btnTitle = false    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view.        myLable.textColor = UIColor.red        myLable.textAlignment = .center        myLable.backgroundColor = UIColor.yellow        myLable.text = "北京天安门"        myLable.font = UIFont.boldSystemFont(ofSize: 16)        self.view.addSubview(myLable)        self.btnTitle = true        myBtn = UIButton.init(type: UIButtonType.roundedRect)        myBtn?.frame = CGRect(x: 20, y: 120, width: 100, height: 30)        myBtn?.setTitle("播放", for: UIControlState.normal)        myBtn?.setTitleColor(UIColor.blue, for: UIControlState.normal)        myBtn?.setTitle("暂停", for: UIControlState.selected)        myBtn?.setTitleColor(UIColor.red, for: UIControlState.selected)        myBtn?.addTarget(self, action: #selector(btnPress(sender:)), for: UIControlEvents.touchUpInside)        self.view.addSubview(myBtn!)        textFiled = UITextField.init(frame: CGRect(x: 20, y: 200, width: 160, height: 50))        textFiled?.placeholder = "请输入账号"        textFiled?.borderStyle = .line        textFiled?.textAlignment = .center        textFiled?.textColor = UIColor.red        textFiled?.keyboardType = .default        textFiled?.clearButtonMode = .whileEditing        textFiled?.clearsOnBeginEditing = true        textFiled?.isSecureTextEntry = false        textFiled?.autocapitalizationType = .allCharacters  //全部大写        textFiled?.delegate = self        self.view.addSubview(textFiled!)    }    func btnPress(sender:UIButton) -> Void {        sender.isSelected = !sender.isSelected    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {        super.touchesBegan(touches, with: event)        self.view.endEditing(true)    }    func textFieldShouldReturn(_ textField: UITextField) -> Bool {        textFiled?.resignFirstResponder()        return true    }    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {        //获取目前textfield控件中的文本        let text = textField.text        var newText = (text! as NSString).replacingCharacters(in: NSMakeRange(range.location, range.length), with: string)        return newText.characters.count <= 8;    }**## 标题 ##//在NewsViewController 文件中-----------------------------**UIViewController,UITableViewDataSource,UITableViewDelegate {    var datas:Array<News>?    var tableView:UITableView?    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {        let onenNews = self.datas?[indexPath.row]        let detailVC = DetailViewController()        detailVC.detailURL = onenNews?.weburl        self.navigationController?.pushViewController(detailVC, animated: true)    }    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        if let count = datas?.count {            return count        }        return 0    }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        let str = "identifier"        var cell = tableView.dequeueReusableCell(withIdentifier: str)        if cell == nil {            cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: str)        }//        let newsDic = self.datas?[indexPath.row] as!//        Dictionary<String,String>//        //        cell?.textLabel?.text = newsDic["title"]//        //        cell?.detailTextLabel?.text = newsDic["time"]        let oneNew = self.datas![indexPath.row]        cell?.textLabel?.text = oneNew.title        cell?.detailTextLabel?.text = oneNew.time        return cell!    }    override func viewWillAppear(_ animated: Bool) {        self.getURLDatas()    }    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view.        tableView = UITableView.init(frame: self.view.frame, style: UITableViewStyle.plain)        tableView?.dataSource = self        tableView?.delegate = self        self.view.addSubview(tableView!)    }    func getURLDatas() -> Void {        let appkey = "de394933e1a3e2db"        let urlStr = "http://api.jisuapi.com/news/get?channel=头条&start=0&num=20&appkey=\(appkey)"//        let urlString = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "`#%^{}\"[]|\\<> ").inverted)        let url = URL(string:urlStr.addingPercentEscapes(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!)        print(url)        let request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 15.0)        let session = URLSession.shared        let task = session.dataTask(with: request) { (data, response, error) in            if error != nil {                print("错误")                return            }            let obj = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as!                Dictionary<String,Any>            print(obj)            let result = obj["result"] as! Dictionary<String,Any>            let list = result["list"] as! Array<Any>            var newsArr:[News]? = []            for item in list {                let newsDic = item as!                    Dictionary<String,String>                let oneNew = News()                oneNew.title = newsDic["title"]                oneNew.time = newsDic["time"]                oneNew.url = newsDic["url"]                oneNew.weburl = newsDic["weburl"]                newsArr?.append(oneNew)            }            self.datas = newsArr            //回到Ui主线程刷新表格            DispatchQueue.main.async(execute: {                 self.tableView?.reloadData()            })        }        task.resume()    }DetailViewController   **## 创建 OC 的 工程 ##//在DetailViewController.h 文件中-----------------------------** @property(nonatomic,strong)NSString *detailURL; // **## 创建 OC 的 工程 ##//在DetailViewController.m 文件中-----------------------------**- (void)viewWillAppear:(BOOL)animated {    [super viewWillAppear:animated];    NSString *urlStr = [self.detailURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//    urlStr = [self.detailURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet];    NSURL *url = [NSURL URLWithString:urlStr];    NSURLRequest *req = [NSURLRequest requestWithURL:url];    [self.webView loadRequest:req];}**## 创建 OC 的 工程 ##// 继承: NSObject  在News.h  文件中-----------------------------**@property(nonatomic,strong)NSString *title;@property(nonatomic,strong)NSString *time;@property(nonatomic,strong)NSString *url;@property(nonatomic,strong)NSString *weburl;
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 恶意骚扰扣12分怎么办 新店开张交保证金被骗了怎么办 支付宝蚂蚁花呗逾期怎么办 被注销的微信怎么办 花呗有些不能用怎么办 实体店生意不好做怎么办 电器实体店生意越来越差怎么办 开业第一天不吉利怎么办 美容店开业第一天没人怎么办 淘宝店铺没有人访问怎么办 淘宝店铺没有人问怎么办 淘宝申请退款后店铺关闭怎么办 宝贝详情怎么改不了怎么办 改详情页后被删除宝贝怎么办 淘宝网商贷生意不好还不了怎么办 英国遗失在酒店物品怎么办 班福法则首位是0怎么办 同事能力比你强怎么办 新买的木板床响怎么办 笔记本键盘驱动坏了怎么办 云柜快递超时了怎么办 毕业设计被老师发现抄的怎么办 地板颜色太深了怎么办 皮质鞋子破皮了怎么办 吃了蜘蛛丝会怎么办 南京高二分班不公平怎么办? 高中分班考试没考好怎么办 实木门上的伸缩缝太深怎么办 mac点关机没反应怎么办 被压倒扁的易拉罐怎么办 白色车漏底漆了怎么办 客厅对着卧室门怎么办 老公不上进还懒怎么办 二胡按弦手指分不开怎么办 酷塑做完后疼痛怎么办 冷冻治疗后水泡破了怎么办 冷冻治疗的水泡破了怎么办? 冷冻治疗水泡破了怎么办 脚上冷冻后起泡怎么办 刺猴冷冻后起泡怎么办 隔壁太吵怎么办阴招