用Swift语言 来写表格

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

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

这里写图片描述


//在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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值