Skip to content

Releases: josercc/DeveloperGist

2022年开发笔记第一期

05 Jan 02:09
7d8577c
Compare
Choose a tag to compare

解决 Dart 打印日志打印不全

我们测试了[print] [debugPrint] [log] 三个函数

分别打印 10000行的日志

  • 【print】函数打印几百个字符就停止打印
  • 【debugPrint】虽然可以打印完毕 但是耗时 40秒
  • 【log】瞬间打印完毕

请使用【log】函数打印日志

修复 Center 组件宽度被拉长

image-20220112151324509我准备封装一个这个组件,高度为固定40,左右的Padding分别为40

TextButton(
  onPressed: () {},
  child: Container(
    height: 40,
    decoration: BoxDecoration(
      color: Colors.green,
      borderRadius: BorderRadius.circular(4),
    ),
    child: const Center(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 40),
        child: Text(
          "登录",
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    ),
  ),
)

image-20220112151548794

结果按钮宽度被拉伸了。了解可以通过Center.widthFactor属性进行设置。

如果非空,则将其宽度设置为子宽度乘以该因子。

可以大于也可以小于 1.0,但必须为非负数。

TextButton(
  onPressed: () {},
  child: Container(
    height: 40,
    decoration: BoxDecoration(
      color: Colors.green,
      borderRadius: BorderRadius.circular(4),
    ),
    child: const Center(
      widthFactor: 1,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 40),
        child: Text(
          "登录",
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    ),
  ),
)

我们设置1 ,代表等于child的宽度。

修复 Column 自动拉伸。

在做这个效果过程中。

Container(
  constraints: const BoxConstraints(
    minHeight: 90,
    minWidth: 90,
  ),
  decoration: BoxDecoration(
    color: Colors.black,
    borderRadius: BorderRadius.circular(4),
  ),
  padding: const EdgeInsets.all(15),
  child: Column(
    children: const [
      CircularProgressIndicator(
        color: Colors.white,
        strokeWidth: 2,
      ),
      SizedBox(
        height: 15,
      ),
      Text(
        "加载中",
        style: TextStyle(color: Colors.white),
      ),
    ],
  ),
)

A851367D-3FBC-4A19-BB7E-6A5C75AE0B0C-38609-000014A93D390563

但是我们的组件纵向铺满了,这不是我们要的效果呀。

MainAxisSize mainAxisSize = MainAxisSize.max,

查询到ColumnmainAxisSize属性默认为MainAxisSize.max,那我们设置MainAxisSize.min是不是就可以了呀。

Container(
  constraints: const BoxConstraints(
    minHeight: 90,
    minWidth: 90,
  ),
  decoration: BoxDecoration(
    color: Colors.black,
    borderRadius: BorderRadius.circular(4),
  ),
  padding: const EdgeInsets.all(15),
  child: Column(
    mainAxisSize: MainAxisSize.min,
    children: const [
      CircularProgressIndicator(
        color: Colors.white,
        strokeWidth: 2,
      ),
      SizedBox(
        height: 15,
      ),
      Text(
        "加载中",
        style: TextStyle(color: Colors.white),
      ),
    ],
  ),
)

421E78AC-04CD-4744-BE34-10D1E4C0E75C-38609-000014DA4C5F6AC3

showMaterialModalBottomSheet 不支持 Hot Reload

将 showMaterialModalBottomSheet builder内容单独提炼一个Widget即可

Flutter 怎么去掉 AppBar 底部阴影

设置 elevation = 0 即可

2021年开发笔记第一期

16 Dec 03:23
5969bbc
Compare
Choose a tag to compare

iOS13之后怎么获取Key Window

static var keyWindow:UIWindow? {
    if #available(iOS 13.0, *) {
        return UIApplication.shared.connectedScenes
            .filter({$0.activationState == .foregroundActive})
            .compactMap({$0 as? UIWindowScene})
            .first?.windows
            .filter({$0.isKeyWindow})
            .first
    } else {
        return UIApplication.shared.windows
            .filter({$0.isKeyWindow})
            .first
    }
}

'xxx_App' is annotated with @main and must provide a main static function of type () -> Void or () throws -> Void. Inheritance from non-protocol type 'App'

谷歌了半天,很多人都遇到过,但是都不能解决我的问题,后来研究发现,我项目存在一样的App名字的Struct,带上模块名字就修复了。

@main
struct Win_App: SwiftUI.App {
    ...
}

SwiftUI 怎么在任何 Function 中实行跳转

struct ContentView: View {
  	/// 控制何时进行跳转
    @State var action: Bool = false
    var body: some View {
        NavigationView {
            HStack(spacing:0) {
            		/// NavigationLink 返回 `EmptyView` 不污染界面
                NavigationLink(destination: destination, isActive: $action) {
                    EmptyView()
                }
                Text("Click me!")
                    .onTapGesture {
                        self.clicked()
                    }
            }
        }
    }
    func clicked() {
        /// 执行跳转
        action = true
    }
}

隐藏返回按钮文本

let backButtonAppearance = UIBarButtonItemAppearance()
backButtonAppearance.normal.titleTextAttributes = [
    .font : UIFont.systemFont(ofSize: 0),
]
appearance.backButtonAppearance = backButtonAppearance

修改 SwiftUI 返回按钮的颜色

NavigationView {
	...
}
.accentColor(.black)

需要注意的是官方说accentColor已经要废弃了,Use the asset catalog's accent color or View.tint(_:) instead."

但是替换为 tint不起作用。

隐藏 SwiftUI 的 UITabbar

需要在需要隐藏界面进行设置

struct PalletBindBoxNumberPage: View {
    ...
    var body: some View {
        ...
        .onAppear {
            App.tabBar?.isHidden = true
        }
        .onDisappear {
            App.tabBar?.isHidden = false
        }
    }
}
struct App {
    static var keyWindow:UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .filter({$0.activationState == .foregroundActive})
                .compactMap({$0 as? UIWindowScene})
                .first?.windows
                .filter({$0.isKeyWindow})
                .first
        } else {
            return UIApplication.shared.windows
                .filter({$0.isKeyWindow})
                .first
        }
    }
    
    static var tabBar:UITabBar? {
        return keyWindow?.rootViewController
            .flatMap({$0.view})
            .flatMap({$0.subviews.first})
            .flatMap({$0.subviews.first})
            .map({$0.subviews})
            .map({$0.compactMap({$0 as? UITabBar})})
            .flatMap({$0.first})
    }
}

巧妙利用 flatMap 和 Map 进行解包

比如我有下面的一个结构

struct Model {
	let age:Int?
}
let model:Model?

此时我想让age显示在文本中,你可能这么写

if let age = model?.age {
		Text("\(age)")
} else {
  	Text("")
}

但是使用flatMapmap进行解包

Text(model.flatMap({$0.age}).map({"\($0)"}) ?? "")

2020年开发笔记第一期

16 Dec 03:15
5969bbc
Compare
Choose a tag to compare

SwiftUI中怎么设置选中图片的颜色?

public func accentColor(_ accentColor: Color?) -> some View

Example

import SwiftUI
/// 自定义的Tab
struct CustomTabView<Content:View>: View {
    ///需要展示的内容元祖数组
    /// - Parameter title: 显示标题
    /// - Parameter image: 默认的显示图片
    /// - Parameter selectImage: 选中的图片 图片颜色将由`selectColor`设置
    /// - Parameter content: 对应的内容试图
    let contents:[(title:String, image:UIImage, selectImage:UIImage, content:Content)]
    /// 设置选中图片的前景色
    let selectColor:UIColor
    @State var tabIndex:Int = 0
    var body: some View {
        TabView(selection: $tabIndex) {
            ForEach(0 ..< contents.count) { index in
                contents[index].3
                    .tabItem {
                        TabItemView(title: contents[index].0,
                                    image: contents[index].1,
                                    selectImage: contents[index].2,
                                    index: index,
                                    currentIndex: $tabIndex)
                    }
                    .tag(index)
            }
        }.accentColor(Color(selectColor))
    }
    
}

extension CustomTabView {
    struct TabItemView: View {
        let title:String
        let image:UIImage
        let selectImage:UIImage
        let index:Int
        @Binding var currentIndex:Int
        var body: some View {
            VStack{
                if (currentIndex == index) {
                    Image(uiImage: selectImage)
                } else {
                    Image(uiImage: image.withRenderingMode(.alwaysTemplate))
                }
                Text(title)
            }
        }
    }
}

struct CustomTabView_Previews: PreviewProvider {
    static var previews: some View {
        CustomTabView(contents: [
            ("首页",#imageLiteral(resourceName: "icon_nav_food1"),#imageLiteral(resourceName: "icon_nav_food2"),Text("1")),
            ("首页",#imageLiteral(resourceName: "icon_nav_food1"),#imageLiteral(resourceName: "icon_nav_food2"),Text("2"))
        ], selectColor: .red)
    }
}

img

Swift使用#if DEBUG

1 第一步在Build Settings->Swift Compiler - Custom Flags->"Other Swift Flags" 在Debug新增"-DDBUG"或者"-D DEBUG"
2 第二部Build Settings->Apple LLVM x.x - Preprocessiong->Preprocessor Macros在Debug新增"DEBUG=1"

Flutter 获取当前Widget所有的子树

对于我们常用的StatefulWidgetStatelessWidget我们可以通过下面方法

createElement().debugGetDiagnosticChain()

SwiftUI cornerRadius方法无法给UIViewRepresentable的UIView生成圆角

需要用UIView的方法设置圆角

view.layer.masksToBounds = true
view.layer.cornerRadius = cornerRadius

UIScroolView实现自定义分页

public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        /// 实现自定义分页
        if velocity != .zero {
            /// 如果velocity不为空 则代表是用户快速拖动离开的 则滚动到下一个位置
            /// 获取到当前的索引
            guard let currentIndex = currentShopIndex else {
                return
            }
            var index:Int
            if velocity.x > 0 {
                index = currentIndex + 1
            } else {
                index = currentIndex - 1
            }
            index = max(0, index)
            index = min(index, self.currentDisplayModels.count - 1)
            let point = scrollCellPoint(index: index)
            targetContentOffset.pointee = point
        }
    }

SwiftUI 自定义UINavigationBar背景颜色

struct NavigationBarModifier: ViewModifier {
    var backgroundColor: UIColor?
    init( backgroundColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = .clear
        coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
        
        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
        UINavigationBar.appearance().tintColor = .white

    }
    
    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}

extension View {
    public func navigationBarBackgroundColor(_ backgroundColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor))
    }
}

SwiftUI .position 定位不准确

因为position是按照中心点进行偏移定位的

2022年开发笔记第二期

06 Feb 08:26
7d8577c
Compare
Choose a tag to compare
Pre-release

Flutter 中 Provider 如何监听 List 的更新

不要直接操作数组,需要先设置新数组

错误操作

list.add("hello");
notifyListeners()
list.add("hello");
list = [...list];
notifyListeners()

正确操作

list = [...list];
list.add("hello");
notifyListeners();