Swift页面的跳转和返回

之前一直使用的OC,现在也有不少人使用Swift,我也尝试一下,写一个简单又基础的功能:页面的跳转和返回。这里将显示几个swift文件的代码。

文件Common.swift的代码:

//
//  Common.swift
//  MySwiftProject
//
//  Created by ChengJh on 2024/5/15.
//  Copyright © 2024 CompanyName. All rights reserved.
//

import SwiftUI


extension Color {
  
  /* 使用示例:let customColor = Color(hex: "#123456"); */
  init(hex: String) {
    let scanner = Scanner(string: hex)
    /* 下划线的作用:我们不关心后面函数返回的结果, 所以使用下划线忽略它。 */
    _ = scanner.scanString("#") // 跳过'#'字符。
    
    var rgbValue: UInt64 = 0
    scanner.scanHexInt64(&rgbValue)
    
    let r = Double((rgbValue & 0xFF0000) >> 16) / 255.0
    let g = Double((rgbValue & 0xFF00) >> 8) / 255.0
    let b = Double(rgbValue & 0xFF) / 255.0
    
    self.init(red: r, green: g, blue: b)
  }
  
}

文件ContentView.swift的代码:

//
//  ContentView.swift
//  MySwiftProject
//
//  Created by ChengJh on 2024/5/15.
//

import SwiftUI

struct ContentView: View {
  var body: some View {
#if DEBUG
    // 打印日志。
    print("test-log");
#endif
    return NavigationView {
      VStack(alignment: .center) {
        Text("Hello, world!")
        NavigationLink(
          destination: SecondView()
        ) {
          Text("Enter SecondView")
            // foregroundColor设置文字颜色。
            .foregroundColor(.white)
            .padding(10)
        }
        .background(Color(hex: "#4982f5"))
        .border(.red, width: 2)
        .cornerRadius(5)
        // Spacer是一个占据剩余空间的视图元素, 可以帮助我们实现更灵活的布局。
        Spacer()
      }
      .frame(width: UIScreen.main.bounds.width)
      .padding(EdgeInsets(top: 50, leading: 0, bottom: 0, trailing: 0))
      .background(Color("#f3f3f3"))
      //.background(.orange)
      .navigationBarHidden(false)
      .navigationViewStyle(.stack)
      .navigationBarTitle("首页", displayMode: .inline);
    }
  }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        // 注: 若内容体只有一条语句 则可省略关键字return。
        ContentView()
    }
}

文件SecondView.swift的代码:

//
//  SecondView.swift
//  MySwiftProject
//
//  Created by ChengJh on 2024/5/15.
//  Copyright © 2022 CompanyName. All rights reserved.
//

import SwiftUI

struct SecondView: View {
  @Environment(\.presentationMode) var presentationMode;
  
  var body: some View {
#if DEBUG
    // 打印日志。
    print("second-log");
#endif
    return VStack {
      Text("Hello, second!")
      .padding()
      Button("Goback") {
        presentationMode.wrappedValue.dismiss();
      }
      //Spacer是一个占据剩余空间的视图元素, 可以帮助我们实现更灵活的布局。
      Spacer()
    }
    .navigationBarTitle("Second");
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值