Swift基础Swift - UI

1、项目创建、导航栏、标签栏

2020-03-01  本文已影响0人  爱玩游戏的iOS菜鸟

项目创建

AppDelegate、SceneDelegate

iOS13之前,Appdelegate的职责全权处理App生命周期和UI生命周期
iOS13之后,Appdelegate的职责是

  1. 处理 App 生命周期
  2. 新的 Scene Session 生命周期

而UI的生命周期则交给新增的SceneDelegate处理,因此如果需要设置根视图控制器有以下3种方法:

  1. 如果应用不使用像ipad的多窗口,把info.plist文件里的 Application Scene Manifest 删掉,并删掉Scenedelegate相关文件,在APPdelegate中删掉 新增的Scenedelegate相关方法,添加一个window属性,并在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中初始化window
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        window?.makeKeyAndVisible()
        window?.rootViewController = TabBarController()
        return true
    }
  1. 在- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions 中初始化window
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        
        window = UIWindow(windowScene: windowScene)
        window?.frame = windowScene.coordinateSpace.bounds
        window?.backgroundColor = UIColor.white
        window?.rootViewController = TabBarController()
        window?.makeKeyAndVisible()
    }
  1. 在Main.storyboard中设置根视图控制器,window属性将自动初始化并附加到windowScene中
info.plist文件路径更改

如需要将相应默认文件更改路径,则需要将Build Settings中队info.plist文件路径进行更改

cocoaPods导入三方库

cocoaPods安装及使用教程
示例写法:

platform :ios, '13.0'

use_frameworks!

target 'Projectname' do
  pod 'RxSwift', '~> 5'
  pod 'RxCocoa', '~> 5'
  pod 'Alamofire'
  pod 'Kingfisher'
  pod 'KakaJSON'
  pod 'MJRefresh'

end
info.plist文件路径更改

导航栏

NavigationController
import UIKit

fileprivate let defaultFont = UIFont.systemFont(ofSize: 17)
fileprivate let defaultColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)

class NavigationController: UINavigationController {
    
    var textColor: UIColor?{
        didSet{
            configNavigateTitle()
        }
    }
    
    var textFont: UIFont?{
        didSet{
            configNavigateTitle()
        }
    }
    
    var leftItemImageName: String?

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        let textAttrs: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: defaultColor, NSAttributedString.Key.font: defaultFont]
        navigationBar.titleTextAttributes = textAttrs

        navigationBar.isTranslucent = false
        navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor.orange), for: UIBarMetrics.default)
    }
    
    private func configNavigateTitle() {
        let textAttrs: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: textColor ?? defaultColor, NSAttributedString.Key.font: textFont ?? defaultFont]
        navigationBar.titleTextAttributes = textAttrs
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        viewController.navigationItem.hidesBackButton = true
        
        if viewControllers.count > 0 {
            let button = UIButton(type: UIButton.ButtonType.custom)
            button.setTitle("", for: UIControl.State.normal)
            button.setTitleColor(UIColor.white, for: UIControl.State.normal)
            button.setTitleColor(UIColor.lightGray, for: UIControl.State.highlighted)
            //button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            
            let backName = leftItemImageName ?? "back"
            button.setImage(UIImage(named: backName), for: .normal)
            button.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
            
            button.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
            button.addTarget(self, action: #selector(backPop), for: UIControl.Event.touchUpInside)
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
            
            viewController.hidesBottomBarWhenPushed = true
        }
        
        super.pushViewController(viewController, animated: animated)
    }

    @objc func backPop() {
        popViewController(animated: true)
    }


}

标签栏

TabbarController
class TabBarController: UITabBarController, UITabBarControllerDelegate {

    var currentIndex: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        setValue(Tabbar(), forKeyPath: "tabBar")
        tabBar.barTintColor = UIColor.white
        tabBar.isTranslucent = false
        
        //设置标签栏黑线清除
        //if #available(iOS 13, *) {
            //let appearance = tabBar.standardAppearance.copy()
            //appearance.backgroundImage = UIImage.imageWithColor(UIColor.clear)
            //appearance.shadowImage = UIImage.imageWithColor(UIColor.clear)
            //tabBar.standardAppearance = appearance
        //} else {
            tabBar.shadowImage = UIImage.imageWithColor(UIColor.clear)
            tabBar.backgroundImage = UIImage.imageWithColor(UIColor.clear)
        //}
        
        //设置标签栏阴影
        tabBar.layer.shadowColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1).cgColor
        tabBar.layer.shadowOffset = CGSize(width: 0, height: -3)
        tabBar.layer.shadowOpacity = 0.2;
        
        addchildVC(HomeChildViewController.self, "首页", "tabbar_home")
        addchildVC(AroundViewController.self, "发现", "tabbar_channel")
        addchildVC(CircleViewController.self, "圈子", "tabbar_circle")
        addchildVC(MessageViewController.self, "消息", "tabbar_msg")
        addchildVC(MineViewController.self, "我的", "tabbar_mine")
        
        selectedIndex = 1 //首次点击
    }
    
    //UITabbarController已经遵守了 这里只是重写
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        let selectIndex = tabBar.items?.firstIndex(of: item)
        
        //声明的私有属性
        if currentIndex != selectIndex{
            tabbarItemAnimationWithIndex(index: selectIndex!)
        }
    }
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        //return NO;不能显示选中的控制器
        return true
    }
    
    func addchildVC(_ child:UIViewController.Type, _ name: String, _ image: String) {
        let childVC = NavigationController(rootViewController: child.init());
        childVC.title = name;
        
        childVC.tabBarItem.image = UIImage(named: image)?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
        childVC.tabBarItem.selectedImage = UIImage(named: "\(image)_active")?.withRenderingMode(.alwaysOriginal)
        
        childVC.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 1), NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0)], for: UIControl.State.normal)
        childVC.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.init(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0)], for: .selected)
        
        //设置 角标颜色 大小
        //childVC.tabBarItem.setBadgeTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12.0)], for: UIControl.State.normal)

        addChild(childVC)
    }
    
    func tabbarItemAnimationWithIndex(index i: Int) {
        let tabbarItem : [UIView] = tabBar.subviews.lazy.filter{ $0 is UIControl }
        
        let pulse = CABasicAnimation.init(keyPath: "transform.scale")
        pulse.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)
        pulse.duration = 0.1
        pulse.repeatCount = 1
        pulse.autoreverses = true
        pulse.fromValue = NSNumber.init(value: 1.0)
        pulse.toValue = NSNumber.init(value: 0.7)
        
        let itemView = tabbarItem[i]
        itemView.layer.add(pulse, forKey: "")
        self.currentIndex = i
    }
}
Tabbar
class Tabbar: UITabBar {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        for button in subviews where button is UIControl{
            
            var frame = button.frame
            frame.origin.y -= 2
            button.frame = frame

        }
    }
    
}
上一篇 下一篇

猜你喜欢

热点阅读