【好书】项目学习笔记 3

【好书】是我第一个看到用代码来写UI界面的项目,非常有趣,下面是我今天学习的内容。

1.新建NavigationView

func setNavigationBar() {
        let navigationView = UIView(frame: CGRect(x: 0, y: -20, width: SCREEN_WIDTH, height: 65))
        navigationView.backgroundColor = UIColor.white
        self.navigationController?.navigationBar.addSubview(navigationView)
        
        let addButton = UIButton(frame: CGRect(x: 20, y: 20, width: SCREEN_WIDTH, height: 45))
        addButton.setImage(UIImage(named: "plus circle"), for: UIControlState.normal)
        addButton.setTitleColor(UIColor.black, for: .normal)
        addButton.setTitle("     新建书评", for: .normal)
        addButton.titleLabel?.font = UIFont(name: MY_FONT, size: 17)
        addButton.contentHorizontalAlignment = .left    //文字居左
        
        addButton.addTarget(self, action: #selector(pushViewController.pushBook), for: UIControlEvents.touchUpInside)
        navigationView.addSubview(addButton)
    }

2.跳转另一个视图

func pushBook() {
        let vc = pushNewBookViewController()
        GeneralFactory.addTitleWithTitle(target: vc, title1: "关闭", title2: "发布")
        self.present(vc, animated: true, completion: nil)
    }

3.工厂模式实现添加“关闭”和发布两个按钮

首先新建一个 class 继承自 NSObject,名为 GeneralFactory,然后添加静态方法 static func,听老师讲这个类似于 Objective-C 中的类方法,不用声明,直接使用。

static func addTitleWithTitle(target: UIViewController, title1: String = "关闭", title2: String = "确认") {
        let btn1 = UIButton(frame: CGRect(x: 10, y: 20, width: 40, height: 20))
        btn1.setTitle(title1, for: .normal)
        btn1.contentHorizontalAlignment = .left
        btn1.setTitleColor(MAIN_RED, for: UIControlState.normal)
        btn1.titleLabel?.font = UIFont(name: MY_FONT, size: 17)
        target.view.addSubview(btn1)
        
        let btn2 = UIButton(frame: CGRect(x: SCREEN_WIDTH - 50, y: 20, width: 40, height: 20))
        btn2.setTitle(title2, for: .normal)
        btn2.contentHorizontalAlignment = .right
        btn2.setTitleColor(MAIN_RED, for: UIControlState.normal)
        btn2.titleLabel?.font = UIFont(name: MY_FONT, size: 17)
        target.view.addSubview(btn2)
        
        btn1.addTarget(target, action: #selector(AVSession.close), for: .touchUpInside)
        btn2.addTarget(target, action: Selector(("sure")), for: .touchUpInside)
        
    }

使用方法如下

GeneralFactory.addTitleWithTitle(target: vc, title1: "关闭", title2: "发布")
Comments
Write a Comment