Swift - 舍友App (00)

文件图例.png
AppDelegate代码.png
self.window = UIWindow(frame:UIScreen.main.bounds)
        self.window?.backgroundColor = UIColor.white
        self.window?.makeKeyAndVisible()
        //选择引导页还是主视图控制器
        //获取用户偏好设置类
        let user = UserDefaults.standard

        let isFirst = user.bool(forKey: "isFirst")

        if isFirst {//为真显示主视图

            let mainVC = MainViewController()

            self.window?.rootViewController = mainVC
        }else{//引导页

            let guideVC = GuideViewController()

            self.window?.rootViewController = guideVC
        }

HomeViewController.swift代码如下:

import UIKit

class HomeViewController: UITableViewController {
    //表头视图上的轮播图
    var scrollView:UIScrollView!
    //点点
    var pageCotrol:UIPageControl!
    //定时器
    var timer:Timer?
    //重用标识
    let amenuCell = "cell"
    override func loadView() {
        self.tableView = UITableView(frame: UIScreen.main.bounds, style: .grouped)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        self.setNavigationBar()

        self.setHeaderView()

        //注册cell
        self.tableView.register(MenuCell.self, forCellReuseIdentifier: amenuCell)

        self.tableView.separatorStyle = .none
        
        //添加定时器
        self.timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)


    }
    //设置导航栏的方法
    func setNavigationBar() {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        //设置导航栏样式
        self.navigationController?.navigationBar.barStyle = .blackOpaque
        //设置导航栏的shadowImage(就是一根白线,可细了)颜色
        self.navigationController?.navigationBar.shadowImage = UIImage()
        //隐藏导航栏
//        self.navigationController?.navigationBar.isHidden = true
        //将带有导航栏时,scrrollView或者scrrollView的子类,布局方式调整到以屏幕左上角为原点
        self.automaticallyAdjustsScrollViewInsets = false
    }
    //表头视图
    func setHeaderView(){

        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 160))

        headerView.backgroundColor = UIColor.cyan

        self.scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 160))

        self.scrollView.contentSize = CGSize(width: CGFloat(CircleImageCount + 2) * KScreenWidth, height: 160)

        self.scrollView.isPagingEnabled = true

        self.scrollView.showsHorizontalScrollIndicator = false
        //设置偏移量
        self.scrollView.contentOffset.x = KScreenWidth
        //设置代理
        self.scrollView.delegate = self
        for i in 0..<(CircleImageCount + 2) {
            let imageView = UIImageView(frame: CGRect(x: CGFloat(i) * KScreenWidth, y: 0, width: KScreenWidth, height: 160))
            if i == 0 {
                imageView.image = UIImage(named: String(format: "house%d.jpg", CircleImageCount))
            }else if i>0 && i<(CircleImageCount + 1){
                imageView.image = UIImage(named: String(format: "house%d.jpg", i))
            }else{
                imageView.image = UIImage(named: "house1.jpg")
            }
            self.scrollView.addSubview(imageView)

        }
        headerView.addSubview(scrollView)

        self.pageCotrol = UIPageControl(frame: CGRect(x: (KScreenWidth - 200)*0.5, y: 140, width: 200, height: 20))

        self.pageCotrol.currentPageIndicatorTintColor = UIColor.cyan

        self.pageCotrol.pageIndicatorTintColor = UIColor.black

        self.pageCotrol.numberOfPages = CircleImageCount

        headerView.addSubview(pageCotrol)

        self.tableView.tableHeaderView = headerView
    }
    //实现scrollView的代理方法
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//        super.scrollViewDidEndDecelerating(scrollView)
        //偏移了多少个屏幕的宽
        if scrollView == self.scrollView {
            let page = Int(scrollView.contentOffset.x / KScreenWidth)

            self.pageCotrol.currentPage = 0

            if page == 6 {
                scrollView.contentOffset.x = KScreenWidth
            }else if page == 0 {
                scrollView.contentOffset.x = CGFloat(CircleImageCount) * KScreenWidth
                self.pageCotrol.currentPage = CircleImageCount - 1
            }else{
                self.pageCotrol.currentPage = page - 1
            }
        }


    }
    //MARK: - 定时器关联方法
    func timerAction() {
        //获取页数
        let page = self.scrollView.contentOffset.x / KScreenWidth
        if page == 5 {//页数==5返回第一张
            self.scrollView.contentOffset.x = KScreenWidth
            self.pageCotrol.currentPage = 0
        }else{
            self.scrollView.contentOffset.x = (page + 1) * KScreenWidth
            self.pageCotrol.currentPage = Int(page)

        }


    }
    //开始拖拽触发的方法
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollView == self.scrollView {
            self.timer?.invalidate()
            self.timer = nil
        }
    }
    //停止拖拽触发的方法
    override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView == self.scrollView {
            self.timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        }
    }
    //区尾视图

    //cell
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 3
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: amenuCell, for: indexPath) as! MenuCell
        if indexPath.row == 0 {
            //titleLable
            cell.titleLable.text = "  ◆推荐房源"
            //picView
            cell.picView.image = UIImage(named: "home_cell1.jpg")

            return cell
        }else if indexPath.row == 1{
            //titleLable
            cell.titleLable.text = "  ◆社区生活"
            //picView
            cell.picView.image = UIImage(named: "home_cell2.jpg")
            return cell

        }else{
            cell.titleLable.text = "  ◆分享活动"
            cell.picView.image = UIImage(named: "home_cell3.jpeg")
            return cell

        }


    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 197
    }

    //头部视图
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 206))
        sectionView.backgroundColor = UIColor.white

        for i in 0..<MenuButtonCount {
            let amenuView = MenuView()

            if i < 3 {
                //布第一行菜单按钮
                amenuView.frame = CGRect(x: 40 + i * (59 + 59), y: 20, width: 59, height: 80)


            }else{
                //布第二行菜单按钮
                amenuView.frame = CGRect(x: 40 + (i - 3) * (59 + 59), y: 109, width: 59, height: 80)
}
                //给控件MenuView上的子控件赋值
                amenuView.iconView.image = UIImage(named: MenuSouce[i]["image"]!)

                amenuView.titleLable.text = MenuSouce[i]["title"]

                amenuView.titleLable.font = UIFont.systemFont(ofSize: 13.0)

                amenuView.titleLable.textColor = UIColor.black
            
                amenuView.tag = 300 + i
                //轻拍手势
                let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
                amenuView.addGestureRecognizer(tap)

            sectionView.addSubview(amenuView)
        }
        return sectionView
    }
    //MARK:- 轻拍手势的关联方法
    //"title":"整租", "image":"ic_home_The entire rent_normal"],["title":"合租", "image":"ic_home_Flat-share_normal"], ["title":"短租", "image":"ic_home_Short rent_normal"], ["title":"服务", "image":"ic_home_service_normal"], ["title":"室友", "image":"ic_home_roommate_normal"], ["title":"收藏", "image":"ic_home_Collection_normal"
    func tapAction(sender:UITapGestureRecognizer){
        let tapView = sender.view as! MenuView
        switch tapView.tag {
        case 300:
            print("整租")
        case 301:
            print("合租")
        case 302:
            print("短租")
        case 303:
            print("服务")
        case 304:
            print("室友")
        case 305:
            print("收藏")
        default:
            print("BUG")
        }

    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        return 206
    }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

MenuView.swift代码如下:

import UIKit

class MenuView: UIView {

    var iconView:UIImageView!
    var titleLable:UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupViews()
    }
    //定义UIImageView和UILabel
    func setupViews() {
        //frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height * 0.7)
        iconView  = UIImageView()

//        iconView.backgroundColor = UIColor.cyan

        self.addSubview(iconView)

        //frame: CGRect(x: 0, y: self.frame.height * 0.7, width: self.frame.width, height: self.frame.height * 0.3)
        titleLable = UILabel()

//        titleLable.backgroundColor = UIColor.red

        titleLable.textAlignment = .center

        self.addSubview(titleLable)

    }
    //重布局子视图
    override func layoutSubviews() {
        iconView.frame  = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height * 0.7)

        titleLable.frame = CGRect(x: 0, y: self.frame.height * 0.7, width: self.frame.width, height: self.frame.height * 0.3)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

MenuCell.swift代码如下:

import UIKit

class MenuCell: UITableViewCell {

    var titleLable:UILabel!
    var picView:UIImageView!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setupViews()
    }
    func setupViews() {
        picView = UIImageView(frame: CGRect(x: 0, y: 7, width: KScreenWidth, height: 190))
        self.contentView.addSubview(picView)

        titleLable = UILabel(frame: CGRect(x: 0, y: 23, width: 120, height: 21))
        //单纯的修改颜色的透明值
        let backColor = UIColor.white

        backColor.withAlphaComponent(0.5)

        titleLable.backgroundColor = backColor

        self.contentView.addSubview(titleLable)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Base / MainViewController.swift代码如下:

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white

        self.setupViewControllers()

    }
    //
    func setupViewControllers(){
        //首页:Home
        let homeVC = HomeViewController()

        let homeNC = UINavigationController(rootViewController: homeVC)

        homeVC.tabBarItem.title = "Home"

        homeVC.tabBarItem.image = UIImage(named: "ic_me_home_non")

        homeVC.tabBarItem.selectedImage = UIImage(named: "ic_home_home_normal")

        homeVC.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12.0),NSForegroundColorAttributeName:ThemeColor], for: .selected)
        //活动:Activity
        let activityVC = ActivityViewController()

        let activityNC = UINavigationController(rootViewController: activityVC)

        activityVC.tabBarItem.title = "Activity"

        activityVC.tabBarItem.image = UIImage(named: "ic_me_activity_non")

        activityVC.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12.0),NSForegroundColorAttributeName:ThemeColor], for: .selected)
        //消息:Messages
        let messagesVC = MessageViewController()

        let messagesNC = UINavigationController(rootViewController: messagesVC)

        messagesVC.tabBarItem.title = "Messages"

        messagesVC.tabBarItem.image = UIImage(named: "ic_me_news_non")

        messagesVC.tabBarItem.badgeValue = "1"

        messagesVC.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12.0),NSForegroundColorAttributeName:ThemeColor], for: .selected)
        //我的:Me
        let meVC = MeViewController()

        let meNC = UINavigationController(rootViewController: meVC)

        meVC.tabBarItem.title = "Me"

        meVC.tabBarItem.image = UIImage(named: "ic_home_me_non")

        meVC.tabBarItem.selectedImage = UIImage(named: "ic_me_me_normal")?.withRenderingMode(.alwaysOriginal)

        meVC.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12.0),NSForegroundColorAttributeName:ThemeColor], for: .selected)
        //添加到数组
        self.viewControllers = [homeNC,activityNC,messagesNC,meNC]
        self.tabBar.tintColor = #colorLiteral(red: 0.07050808519, green: 0.6223047376, blue: 0.5250155926, alpha: 1)

    }
    //选中tabBarItem的时候触发
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        item.badgeValue = nil
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

ConstFile.swift代码如下:

import UIKit
//引导页的个数
let GuideImageCount = 3
//轮播图的个数
let CircleImageCount = 5
//菜单按钮的个数
let MenuButtonCount = 6
//菜单资源
let MenuSouce:[[String:String]] = [
    ["title":"整租", "image":"ic_home_The entire rent_normal"],
    ["title":"合租", "image":"ic_home_Flat-share_normal"],
    ["title":"短租", "image":"ic_home_Short rent_normal"],
    ["title":"服务", "image":"ic_home_service_normal"],
    ["title":"室友", "image":"ic_home_roommate_normal"],
    ["title":"收藏", "image":"ic_home_Collection_normal"]
]
//屏幕的宽
let KScreenWidth = UIScreen.main.bounds.width
//屏幕的高
let KScreenHeight = UIScreen.main.bounds.height
//主题色
let ThemeColor = UIColor(red: 1.0/255, green: 179.0/255, blue: 135.0/255, alpha: 1)

Guide / Controller / GuideViewController.swift代码如下:

import UIKit

class GuideViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
    }
    //输出导航页
    func setupViews(){

        let scrollerView = UIScrollView(frame: UIScreen.main.bounds)

        scrollerView.contentSize = CGSize(width: CGFloat(GuideImageCount) * KScreenWidth, height: CGFloat(KScreenHeight))
        //设置整页滚动
        scrollerView.isPagingEnabled = true
        //弹簧效果
        scrollerView.bounces = false
        //取消底部滚动条
        scrollerView.showsHorizontalScrollIndicator = false

        self.view.addSubview(scrollerView)
        for i in 0..<GuideImageCount {
            let imageView = UIImageView(frame: CGRect(x: CGFloat(i) * KScreenWidth, y: 0, width: KScreenWidth, height: KScreenHeight))

            imageView.image = UIImage(named: String(format: "guide%d", i))

            scrollerView.addSubview(imageView)
            if i == GuideImageCount - 1 {
                imageView.isUserInteractionEnabled = true
                let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
                imageView.addGestureRecognizer(tap)


            }
        }
    }
    //MARK:- 轻拍手势的关联方法
    func tapAction(){
        let user = UserDefaults.standard
        //防止多个值并发
        user.set(true, forKey: "isFirst")
        //同步操作
        user.synchronize()

        let application = UIApplication.shared

        application.keyWindow?.rootViewController = MainViewController()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,657评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,662评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,143评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,732评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,837评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,036评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,126评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,868评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,315评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,641评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,773评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,859评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,584评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,676评论 2 351

推荐阅读更多精彩内容