Android、iOS页面跳转与传值

1. Android--Activity的传值和回传值

  • 通过startActivity来进行Activity的传值

页面一

//通过setClass方法来指定我们要跳转的Activity
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);

//通过setAction方法来我们要完成的一个action操作
Intent  intent = new Intent();
intent.setAction("com.xiaoluo.android_intent.second");

      <activity 
          android:name="com.xiaoluo.android_intent.SecondActivity"
            android:label="SecondActivity">
            <intent-filter>
                <action android:name="com.xiaoluo.android_intent.second"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>

页面二

//    得到跳转到该Activity的Intent对象
        Intent intent = getIntent();
        int age = intent.getIntExtra("com.xiaoluo.android_intent.age", 10);
        String name = intent.getStringExtra("com.xiaoluo.android_intent.name");
        Bundle bundle = intent.getBundleExtra("bundle");
        String world = bundle.getString("hello");
        
        Log.i(TAG, age + ", " + name + ", " + world);
         
        textView.setText(name + " : " + age + ", " + world);
        
        System.out.println(intent);
  • 通过startActivityForResult方法类得到Activity的回传值

Activity一

            Intent intent = new Intent();
            intent.putExtra("message", editText1.getText().toString().trim() + " + " + editText2.getText().toString().trim() + " = ?");
            intent.setClass(MainActivity.this, SecondActivity.class);
/*
 * 如果希望启动另一个Activity,并且希望有返回值,则需要使用startActivityForResult这个方法,
 * 第一个参数是Intent对象,第二个参数是一个requestCode值,如果有多个按钮都要启动Activity,则requestCode标志着每个按钮所启动的Activity
 */
            startActivityForResult(intent, 1000);


    /**
     * 所有的Activity对象的返回值都是由这个方法来接收
     * requestCode:    表示的是启动一个Activity时传过去的requestCode值
     * resultCode:表示的是启动后的Activity回传值时的resultCode值
     * data:表示的是启动后的Activity回传过来的Intent对象
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1000 && resultCode == 1001)
        {
            String result_value = data.getStringExtra("result");
            editText3.setText(result_value);
        }
    }

Activity二

 String result = editText.getText().toString().trim();
 Intent intent = new Intent();
 intent.putExtra("result", result);
 /*
 * 调用setResult方法表示我将Intent对象返回给之前的那个Activity,这样就可以在onActivityResult方法中得到Intent对象,
 */
 setResult(1001, intent);
 //    结束当前这个Activity对象的生命
 finish();

  /**
  * 在调用了startActivity方法之后立即调用overridePendingTransition方法,选择页面跳转的动画模式
  */
  overridePendingTransition(0,0);
  • 传输对象

定义一个类

package com.example.jtr.helloworldapplication;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by jtr on 2017/12/5.
 * Parcelable序列化接口
 */

public class User implements Parcelable {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    protected User(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }

    public static final Creator<User> CREATOR = new Creator<User>() {
        @Override
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        @Override
        public User[] newArray(int size) {
            return new User[size];
        }
    };

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;

        User user = (User) o;

        if (getAge() != user.getAge()) return false;
        return getName().equals(user.getName());
    }

    @Override
    public int hashCode() {
        int result = getName().hashCode();
        result = 31 * result + getAge();
        return result;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }
}

在Activity中调用

//Activity一:
 Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
 User user = new User("xiaoming",22);
 intent.putExtra("user",user);
 startActivity(intent);
 startActivityForResult(intent,1000);

//Activity二:
 User user =getIntent().getParcelableExtra("user");

2. IOS页面跳转方式

2.1 模态跳转(Model)

  • 模态:一个普通的视图控制器一般只有模态跳转的功能,这个方法是所有视图控制器对象都可以用的。
(void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion
  • 在官方文档中,建议这两者之间通过delegate实现交互。例如使用UIImagePickerController从系统相册选取照片或者拍照,imagePickerController和弹出它的VC之间就通过UIImagePickerControllerDelegate实现交互的。

  • 控制器的中的只读属性:presentedViewController和presentingViewController,他们分别就是被present的控制器和正在presenting的控制器。

  • Modal的效果:默认是新控制器从屏幕的最底部往上钻,直到盖住之前的控制器为止。但可以通过自定义转场来改变展现view的动画,大小,位置,是否移除跳转之前的view.这个效果可以用来模拟ipad特有的Popover弹出框。

  • 需要注意的是,默认他的实现过程是移除跳转之前的控制器的view,并将新的控制器的view展示,但跳转之前的控制器并没有被释放,而是被强引用这的。区别于导航控制器的push。

  • 通过 dismissViewControllerAnimated 来返回前一个界面的。

ModelJumpViewController *mvc = [ModelJumpViewController new];
                [self presentViewController:mvc animated:YES completion:^{
                    NSLog(@"Model跳转后的回调");
                }];

[self dismissViewControllerAnimated:YES completion:^{
                    NSLog(@"test,模态跳转的返回");
                }];

2.2通过Segue跳转

Segue添加
//页面一的.m文件
//执行跳转
[self performSegueWithIdentifier:@"segueJump" sender:nil];

//监听segue方式的页面跳转传值
/*通过sender携带参数*/
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    //获取目标页面对象
    SegueJumpViewController *sjvc = (SegueJumpViewController *)segue.destinationViewController;
    //通过给目标页面的成员变量赋值传输数据
    sjvc.json = @"rootviewMsg";
    //可通过回调方式接受目标页面的返回值
    sjvc.cb = ^NSString *(NSString *msg) {
        NSLog(@"%@",msg);
        return @"来自页面一的传值";
    };
}
//页面二的.h文件
#import "ViewController.h"
typedef NSString * (^callback)(NSString *msg);
@interface SegueJumpViewController : ViewController
@property(nonatomic,copy)NSString *json;
@property(nonatomic,copy)callback cb;
@end

//页面二的.m文件
import "SegueJumpViewController.h"
@interface SegueJumpViewController ()
@end

@implementation SegueJumpViewController
- (IBAction)goBack:(id)sender {
//    [self.navigationController popViewControllerAnimated:YES];
    NSString * msg = self.cb(@"segueCallBackMsg");
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"%@",msg);
    }];
}

2.3 Navigation跳转

原理类似安卓的后退栈
UINavigationController view层级
/*在AppDelegate.h文件中声明*/
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    //定义一个全局变量
    UINavigationController *nav;
}
@property (strong, nonatomic) UIWindow *window;
@end


/*在AppDelegate.m文件中定义根视图和添加导航控制器*/
 //获取Main story
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    //通过ID获取故事板的UIViewController
    ViewController *vc = [story instantiateViewControllerWithIdentifier:@"rootvc"];
    
    //初始化Window对象
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    //初始化根视图
    nav = [[UINavigationController alloc]initWithRootViewController:vc];
    nav.navigationBarHidden = false;
    [nav.navigationController.navigationItem.backBarButtonItem setStyle:UIBarButtonItemStylePlain];
    //设置根视图
    self.window.rootViewController = nav;
    
    //让当前UIWindow变成keyWindow(主窗口)
    [self.window makeKeyWindow];
    //让当前UIWindow变成keyWindow,并显示出来
//    [self.window makeKeyAndVisible];

/*页面一push跳转*/
//获取要跳转的页面
 UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  SegueJumpViewController *sgvc = [story instantiateViewControllerWithIdentifier:@"sgvc"];

 //执行跳转
  [self.navigationController pushViewController:sgvc animated:YES];

/*页面二通过pop返回*/
[self.navigationController popViewControllerAnimated:YES];

2.4Tab

TabBar的结构
添加子视图
//获取storybroad中UITabBarController控制器
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    tabViewController *tab = [story instantiateViewControllerWithIdentifier:@"tabRootView"];
    //设置根视图
    [tab.view.window makeKeyWindow];
    //选择对应的跳转方式
//    [self.navigationController pushViewController:tab animated:YES];
    [self presentViewController:tab animated:YES completion:^{
        
    }];

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,566评论 25 707
  • �感谢大家对前两篇的支持,在第一篇的评论中,简友YouXianMing提出了更好的实现思路,同样在评论中,原动效设...
    柯烂阅读 5,511评论 22 73
  • (题记:丁酉秋分日,随作协到崀山联合采风,随兴而记之) 七绝.遇仙桥 伫立桥头往事悠,青藤老树野花稠。 ...
    白云之外阅读 362评论 0 1
  • 跟我分开后,他竟然这么短的时间内又谈了场恋爱。他不停地跟我讲述他们怎么开始的,怎么结束的,像个小孩子一样,还有点不...
    琰言阅读 176评论 0 0
  • 今天回之前任教的公立学校志愿服务,得以在走廊里采访了幼儿园到五年级的几位老师。在这所学校,幼儿园在一个班,...
    原小虾阅读 1,342评论 0 1