Swift UI学习UITableView and protocol use

Models: UserModel.swift

Views: UserInfoCell.swift

Controllers: RootViewController.swift, DetailViewController.swift


AppDelegate.swift:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?

) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // let rootController = RootViewController(style: UITableViewStyle.Plain) let rootNav = UINavigationController(rootViewController: rootController) self.window!.rootViewController = rootNav // self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } }


UserModel.swift

import Foundation

//
// @brief The model of user, using to store user datas
// @author huangyibiao
//
class UserModel : NSObject {
    var userName: String     ///< store user's name, optional
    var userID: Int          ///< store user's ID
    var phone: String?       ///< store user's telephone number
    var email: String?       ///< store user's email
    
    // designated initializer
    init(userName: String, userID: Int, phone: String?, email: String?) {
        self.userName = userName
        self.userID = userID
        self.phone = phone
        self.email = email
        
        super.init()
    }
}

UserInfoCell.swift:

import Foundation
import UIKit

//
// @brief The cell of showing user infos
// @author huangyibiao
//
class UserInfoCell : UITableViewCell {
    var userNameLabel : UILabel!
    var phoneLabel : UILabel!
    var emailLabel : UILabel!
    
    init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        userNameLabel = UILabel(frame: CGRectMake(30, 0, 100, 44))
        userNameLabel.backgroundColor = UIColor.clearColor()
        userNameLabel.font = UIFont.systemFontOfSize(14)
        self.contentView.addSubview(userNameLabel)
        
        phoneLabel = UILabel(frame: CGRectMake(120, 0, 200, 20))
        phoneLabel.backgroundColor = UIColor.clearColor()
        phoneLabel.font = UIFont.systemFontOfSize(12)
        self.contentView.addSubview(phoneLabel)

        emailLabel = UILabel(frame: CGRectMake(120, 20, 200, 20))
        emailLabel.backgroundColor = UIColor.clearColor()
        emailLabel.font = UIFont.systemFontOfSize(12)
        self.contentView.addSubview(emailLabel)
    }

    func configureCell(userModel: UserModel?) {
        if let model = userModel {
            userNameLabel.text = model.userName
            phoneLabel.text = model.phone
            emailLabel.text = model.email
        }
    }
}


RootViewController.swift:

import Foundation
import UIKit

//
// @brief 作为窗体的rootViewControllor
// @author huangyibiao
//

class RootViewController : UITableViewController, DetailViewControllerDelegate {
    var dataSource = NSMutableArray()
    var currentIndexPath: NSIndexPath?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        for index in 0...12 {
            let model = UserModel(userName: "name:\(index + 1)",
                userID: index, phone: "13877747982", email: "632840804@qq.com")
            dataSource.addObject(model)
        }
        
        self.title = "UITableViewDemo"
    }
    
    override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int  {
        return dataSource.count
    }
    
    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        // can't use static?

let cellIdentifier: String = "UserInfoCellIdentifier" // may be no value, so use optional var cell: UserInfoCell?

= tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UserInfoCell if cell == nil { // no value cell = UserInfoCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } let model: UserModel?

= dataSource[indexPath.row] as? UserModel cell!.configureCell(model) return cell } override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { let detail = DetailViewController() detail.userModel = dataSource[indexPath.row] as?

UserModel detail.delegate = self currentIndexPath = indexPath self.navigationController.pushViewController(detail, animated: true) } func changeItem(forUserModel userModel: UserModel?) { var index = 0 for index = 0; index < dataSource.count; index++ { let model = dataSource[index] as UserModel if model.userID == userModel?.userID { model.phone = userModel?

.phone model.email = userModel?.email tableView.reloadRowsAtIndexPaths([currentIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) break } } } }



DetailViewController.swift:

import Foundation
import UIKit

// this delegate needs a @objc, because @optional is only for objective-c, not for swift
@objc protocol DetailViewControllerDelegate : NSObjectProtocol {
    @optional func changeItem(forUserModel userModel: UserModel?)
}

class DetailViewController : UIViewController {
    var userModel: UserModel?
    var delegate: DetailViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
        self.title = userModel?

.userName let button = UIButton(frame: CGRectMake(10, 200, 300, 40)) button.setTitle("change", forState:UIControlState.Normal) button.backgroundColor = UIColor.redColor() button.addTarget(self, action: "onChangeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } func onChangeButtonClick(sender: UIButton!) { if userModel { userModel!.userName = "ChangeName" // changeItem needs to add a ? to the end, before (), because // this function is optional // delegate?

表示可能没有代理。而changeItem?

表示方法可能没有实现,这样写就算没有实现也没有问题 delegate?.changeItem?

(forUserModel: userModel) self.navigationController.popViewControllerAnimated(true) } } }


效果图:



版权声明:本文博客原创文章,博客,未经同意,不得转载。






本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/4727952.html,如需转载请自行联系原作者


优秀的个人博客,低调大师

微信关注我们

原文链接:https://yq.aliyun.com/articles/369594

转载内容版权归作者及来源网站所有!

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

相关文章

发表评论

资源下载

更多资源
优质分享Android(本站安卓app)

优质分享Android(本站安卓app)

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Oracle Database,又名Oracle RDBMS

Oracle Database,又名Oracle RDBMS

Oracle Database,又名Oracle RDBMS,或简称Oracle。是甲骨文公司的一款关系数据库管理系统。它是在数据库领域一直处于领先地位的产品。可以说Oracle数据库系统是目前世界上流行的关系数据库管理系统,系统可移植性好、使用方便、功能强,适用于各类大、中、小、微机环境。它是一种高效率、可靠性好的、适应高吞吐量的数据库方案。

Apache Tomcat7、8、9(Java Web服务器)

Apache Tomcat7、8、9(Java Web服务器)

Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache、Sun 和其他一些公司及个人共同开发而成。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。

Sublime Text 一个代码编辑器

Sublime Text 一个代码编辑器

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。