一个功能,两个平台,三种语言 -(iOS,Swift,Android)App代码实现对比篇

-调研

话说移动互联网正值风起云涌期间,各路编程高手都是摩拳擦掌,何况企业公司都开始接受现实,走移动办公,信息云端,大数据处理的步伐,在这本该三足鼎立的时刻,微软显得有点步履蹒跚,导致移动端最值得进军的平台被iOS 和 Android 几乎瓜分,这不符合历史轨迹啊,希望 WP 能厚积薄发,重回当年PC时代的辉煌。

-前序

这里就不再指点江山,直奔主题吧,来看看做同样一个功能,在iOS平台和Android平台都是具体如何实现的,代码是如何写的,这里有个分支就是iOS平台开发又分为Objective-C 和 Swift 两种语言,下面就具体来分析实现一个功能,在两个平台里,使用三种语言都是具体怎么来实现的,希望给入门无法判断开始那种语言的朋友一个指引,也能给转型iOS或Android跨平台开发的朋友一点借鉴,看看到底 Objective-C,Swift 和 Java 到底谁才更具有潜力,注意,具体代码实现不讲解,需要有一定的编程经验。

-需求

1,A页面输入 文字 ,点击下一页Push进来B页面,此时B页面显示A页面输入的文字;

2,B页面输入 文字,点击返回Pop到A页面,此时A页面显示B页面输入的文字;

3,即页面传值功能,暂且叫它礼尚往来,全部用纯代码来写;

-实现

一,iOS 之 Objective-C

1,A页面代码;

//MainViewController.m

#import "MainViewController.h"
#import "SubViewController.h"

#define kIPHONE_WIDTH [UIScreen mainScreen].bounds.size.width

@interface MainViewController ()<ExchangeGiftDelegate>
{
    UITextField *inputTextField;
    UILabel *giftLbl;
}

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"礼尚";
    self.view.backgroundColor = [UIColor whiteColor];

    inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 120, kIPHONE_WIDTH-140, 40)];
    inputTextField.placeholder = @"输入要赠送礼品名称";
    inputTextField.borderStyle = UITextBorderStyleLine;
    inputTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:inputTextField];

    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(kIPHONE_WIDTH-100, 120, 80, 40);
    sendBtn.backgroundColor = [UIColor redColor];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sendBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [sendBtn setTitle:@"送礼" forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];

    giftLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 170, kIPHONE_WIDTH-40, 40)];
    giftLbl.backgroundColor = [UIColor lightGrayColor];
    giftLbl.textColor = [UIColor greenColor];
    giftLbl.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:giftLbl];

}

-(void)sendBtnClick:(id)sender
{
    NSLog(@"开始送礼");

    if (inputTextField.text.length>0) {

        [self sendGiftName:inputTextField.text];

        inputTextField.text = @"";

    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"黄色警告" message:@"没有礼物送,不厚道吧" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alertView show];
        [inputTextField becomeFirstResponder];
    }
}

-(void)sendGiftName:(NSString*)name
{
    NSLog(@"开始送礼:%@",name);

    SubViewController *subViewController = [[SubViewController alloc] init];
    subViewController.giftNameStr = name;
    subViewController.delegate = self;
    [self.navigationController pushViewController:subViewController animated:YES];
}

#pragma mark- ExchangeGiftDelegate
-(void)exchangeGiftName:(NSString *)name
{
    giftLbl.text = name;
}

2,B页面代码;

//SubViewController.h

#import <UIKit/UIKit.h>
@protocol ExchangeGiftDelegate <NSObject>
-(void)exchangeGiftName:(NSString *)name;
@end

@interface SubViewController : UIViewController

@property (nonatomic, strong) NSString *giftNameStr;

@property (nonatomic, weak) id<ExchangeGiftDelegate> delegate;

@end

//SubViewController.m

#import "SubViewController.h"

#define kIPHONE_WIDTH [UIScreen mainScreen].bounds.size.width

@interface SubViewController ()
{
    UITextField *inputTextField;
    UILabel *giftLbl;
}

@end

@implementation SubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"往来";
    self.view.backgroundColor = [UIColor whiteColor];

    inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 120, kIPHONE_WIDTH-140, 40)];
    inputTextField.placeholder = @"输入回送的礼品名称";
    inputTextField.borderStyle = UITextBorderStyleLine;
    inputTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:inputTextField];

    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(kIPHONE_WIDTH-100, 120, 80, 40);
    sendBtn.backgroundColor = [UIColor redColor];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sendBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [sendBtn setTitle:@"回礼" forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];

    giftLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 170, kIPHONE_WIDTH-40, 40)];
    giftLbl.backgroundColor = [UIColor lightGrayColor];
    giftLbl.textColor = [UIColor purpleColor];
    giftLbl.textAlignment = NSTextAlignmentCenter;
    giftLbl.text = self.giftNameStr;
    [self.view addSubview:giftLbl];

}

-(void)sendBtnClick:(id)sender
{
    NSLog(@"开始回礼");

    if (inputTextField.text.length>0) {

        [self sendGiftName:inputTextField.text];
        [self.navigationController popViewControllerAnimated:YES];

    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"红色警告" message:@"没有礼物回赠,好小气呀" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alertView show];
        [inputTextField becomeFirstResponder];
    }
}

-(void)sendGiftName:(NSString*)name
{
    if ([self.delegate respondsToSelector:@selector(exchangeGiftName:)]) {
        [self.delegate exchangeGiftName:inputTextField.text];
    }
}

二,iOS 之 Swift

1,A页面代码;

//MainViewController.swift

import UIKit

class MainViewController: UIViewController,ExchangeGiftDelegate {

    let kIPHONE_WIDTH = UIScreen.mainScreen().bounds.size.width

    var inputTextField : UITextField!
    var giftLbl:UILabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "礼尚"
        self.view.backgroundColor = UIColor.whiteColor()

        inputTextField = UITextField(frame: CGRectMake(20, 120, kIPHONE_WIDTH-140, 40))
        inputTextField.placeholder = "输入要赠送礼品名称"
        inputTextField.borderStyle = UITextBorderStyle.Line
        inputTextField.textAlignment = NSTextAlignment.Center
        inputTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
        self.view.addSubview(inputTextField)

        let sendBtn:UIButton = UIButton()
        sendBtn.frame = CGRectMake(kIPHONE_WIDTH-100, 120, 80, 40)
        sendBtn.backgroundColor = UIColor.redColor()
        sendBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        sendBtn.setTitle("送礼", forState: UIControlState.Normal)
        sendBtn.addTarget(self, action: "sendBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(sendBtn)

        //let giftLbl : UILabel = UILabel()
        giftLbl.frame = CGRectMake(20, 170, kIPHONE_WIDTH-40, 40)
        giftLbl.backgroundColor = UIColor.lightGrayColor()
        giftLbl.textColor = UIColor.greenColor()
        giftLbl.textAlignment = NSTextAlignment.Center
        self.view.addSubview(giftLbl)

    }

    func sendBtnClick(sneder:UIButton)
    {
        println("开始送礼");

        sendGiftName()
    }

    func sendGiftName(){

        if inputTextField.text.isEmpty {

            var alert : UIAlertView = UIAlertView(title: "黄色警告", message: "没有礼物送,不厚道吧", delegate: nil, cancelButtonTitle: "知道了")
            alert.show()
            inputTextField.becomeFirstResponder()

        }else{

            sendGiftName(inputTextField.text)
            inputTextField.text = ""
        }
    }

    func sendGiftName(name:NSString){

        var subVC :SubViewController = SubViewController()
        subVC.giftNameStr = self.inputTextField.text;
        subVC.delegate = self;
        self.navigationController?.pushViewController(subVC, animated: true)
    }

    //ExchangeGiftDelegate
    func exchangeGiftName(name: NSString) {
        giftLbl.text = name
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

2,B页面代码;

//SubViewController.swift

import UIKit

@objc protocol ExchangeGiftDelegate{
   optional func exchangeGiftName(name : NSString)
}

class SubViewController: UIViewController {

    let kIPHONE_WIDTH = UIScreen.mainScreen().bounds.size.width

    var inputTextField : UITextField!
    var giftLbl : UILabel = UILabel()

    var giftNameStr : NSString!

    var delegate:ExchangeGiftDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "往来"
        self.view.backgroundColor = UIColor.whiteColor()

        inputTextField = UITextField(frame: CGRectMake(20, 120, kIPHONE_WIDTH-140, 40))
        inputTextField.placeholder = "输入回送的礼品名称"
        inputTextField.borderStyle = UITextBorderStyle.Line
        inputTextField.textAlignment = NSTextAlignment.Center
        inputTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
        self.view.addSubview(inputTextField)

        let sendBtn:UIButton = UIButton()
        sendBtn.frame = CGRectMake(kIPHONE_WIDTH-100, 120, 80, 40)
        sendBtn.backgroundColor = UIColor.redColor()
        sendBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        sendBtn.setTitle("回礼", forState: UIControlState.Normal)
        sendBtn.addTarget(self, action: "sendBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(sendBtn)

        giftLbl.frame = CGRectMake(20, 170, kIPHONE_WIDTH-40, 40)
        giftLbl.backgroundColor = UIColor.lightGrayColor()
        giftLbl.textColor = UIColor.purpleColor()
        giftLbl.textAlignment = NSTextAlignment.Center
        giftLbl.text = giftNameStr
        self.view.addSubview(giftLbl)
    }

    func sendBtnClick(sneder:UIButton)
    {
        sendGiftName()
    }

    func sendGiftName(){

        if inputTextField.text.isEmpty {

            var alert : UIAlertView = UIAlertView(title: "红色警告", message: "没有礼物回赠,好小气呀", delegate: nil, cancelButtonTitle: "知道了")
            alert.show()
            inputTextField.becomeFirstResponder()

        }else{

            delegate?.exchangeGiftName!(inputTextField.text)
            self.navigationController?.popViewControllerAnimated(true)
        }
    }

三,Android 之 Java

1,A页面代码;

//activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/minput"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/msendBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/mname" />

    </LinearLayout>

    <TextView
        android:id="@+id/mgiftname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/minput"
        android:layout_marginTop="20dp"
        android:textSize="40px"
        android:textColor="@color/background_material_dark"
        android:gravity="center" />

</LinearLayout>

//MainActivity.java

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private static final int REQUST_CODE = 0;
    private EditText inputEditText;
    private Button  sendBtn;
    private TextView giftTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("礼尚");

        inputEditText = (EditText)findViewById(R.id.minput);
        sendBtn = (Button)findViewById(R.id.msendBtn);
        giftTextView = (TextView)findViewById(R.id.mgiftname);

        sendBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.i("TAG","送礼");

        String giftName = inputEditText.getText().toString();
        if (giftName.length()>0){

            Intent intent = new Intent(MainActivity.this,SubActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("name", giftName);
            intent.putExtras(bundle);
            startActivityForResult(intent,0);

            inputEditText.setText("");

        }else {

            Toast.makeText(this,"没有礼物送,不厚道吧",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){

            case REQUST_CODE:
            {
                switch (resultCode){
                    case RESULT_OK:
                    {
                        Bundle bundle = data.getExtras();
                        giftTextView.setText(bundle.getString("name"));
                    }
                    break;
                }
            }
            break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}

2,B页面代码;

//activity_sub.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/sinput"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/ssendBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sname" />

    </LinearLayout>

    <TextView
        android:id="@+id/sgiftname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/minput"
        android:layout_marginTop="20dp"
        android:textSize="40px"
        android:textColor="@color/material_blue_grey_900"
        android:gravity="center" />

</LinearLayout>

//SubActivity.java

public class SubActivity extends ActionBarActivity implements View.OnClickListener {

    private EditText inputEditText;
    private Button sendBtn;
    private TextView giftTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);

        inputEditText = (EditText)findViewById(R.id.sinput);
        sendBtn = (Button)findViewById(R.id.ssendBtn);
        giftTextView = (TextView)findViewById(R.id.sgiftname);

        sendBtn.setOnClickListener(this);

        Bundle bundle = this.getIntent().getExtras();
        giftTextView.setText(bundle.getString("name"));

    }

    @Override
    public void onClick(View v) {
        Log.i("TAG", "回礼");

        String giftName = inputEditText.getText().toString();
        if (giftName.length()>0){

            Intent intent = new Intent(SubActivity.this,MainActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("name", giftName);
            intent.putExtras(bundle);
            setResult(RESULT_OK,intent);
            finish();

        }else {

            Toast.makeText(this, "没有礼物回赠,好小气呀", Toast.LENGTH_SHORT).show();
        }
    }
}

//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">礼尚往来</string>
    <string name="action_settings">Settings</string>
    <string name="mname">送礼</string>
    <string name="title_activity_sub">往来</string>
    <string name="sname">回礼</string>

</resources>

-附图(Swift 运行效果)

-总结

代码量:Swift 明显占优势,但是对于习惯OC的人来说,有点乱七八糟,但是非常适合入门朋友,特别是从JS转过来的;

逻辑:OC 和 Swift 基本一致,通过协议委托方式来完成传值,但是安卓采用隐式方式来传递,逻辑上较iOS来显得更合理和易于理解;

总之,三种语言都有自己的风格和写法,具体选择那种,往往和自己之前的工作经验有关系,萝卜青菜,各有所爱吧,希望看完对大家有所启示就好,另外,笔者只是一个代码传道者而已,若有笔误,敬请谅解,原创博客,转载请注明出处,谢谢。

时间: 2024-10-07 23:04:08

一个功能,两个平台,三种语言 -(iOS,Swift,Android)App代码实现对比篇的相关文章

lamp平台三种实现方式

lamp平台的安装实现方式分为三种:rpm包的方式安装,以模块的方式编译安装,以fpm方式工作编译安装的php. 一.rpm包安装php: 在CentOS 6.5系统上以rpm包的方式安装httpd,php,mysq是最容易的一种,php在这种情况下做为httpd的模块来运行,在安装完php对应的rpm包以后,可以在httpd的配置文件目录中查看到php.conf文件,配置文件中定义了加载php模块对应的库文件的定义.当httpd启动进程响应客户的请求时,如果客户端请求的是php页面文件,那么h

前端(一)—— 前端三种语言、

前端三种语言.核心标签.常见标签.标签分类 一.前端 前端即网站前台部分,运在PC端,移动端等浏览器上展现给客户浏览的的网页.随着互联网技术的发展,HTML5,CSS3,前端框架的应用,跨平台响应式网页设计能够适应各种屏幕分辨率,完美的动效设计,给用户带来极高的用户体验.前端技术一般分为前端设计和前端开发,前端设计一般可以理解为网站的视觉设计,前端开发则是网站的前台代码实现,包括基本的HTML和CSS以及JavaScript. 二.HTML.CSS.JavaScript 1.HTML (1)ht

[爱上Swift]第三弹:使用Swift建立App基本基石

搭架子 首先这次我们会主要使用IOS自带的导航Controller为一个APP建立一个简单的基石, 新建一个空的Application并创建3个swift文件,分别命名为:FirstViewController,SecondViewController,ThirdViewController; 同时在三个Swift的Controller中重写继承类的viewDidLoad()方法: override func viewDidLoad(){ super.viewDidLoad(); } 在整个程序

让一个元素垂直水平居中的三种方法

第一种方法: div.box{ weight:200px; height:400px; <!--把元素变成定位元素--> position:absolute; <!--设置元素的定位位置,距离上.左都为50%--> left:50%; top:50%; <!--设置元素的左外边距.上外边距为宽高的负1/2--> margin-left:-100px; margin-top:-200px; } *兼容性好;缺点:必须知道元素的宽高 ------------- 第二种方法:

让一个元素垂直水平居中的三种方法【转】

第一种方法: div.box{ weight:200px; height:400px; <!--把元素变成定位元素--> position:absolute; <!--设置元素的定位位置,距离上.左都为50%--> left:50%; top:50%; <!--设置元素的左外边距.上外边距为宽高的负1/2--> margin-left:-100px; margin-top:-200px; } *兼容性好;缺点:必须知道元素的宽高 ------------- 第二种方法:

三种不同查找算法实际查找性能的对比

   一.查找问题的介绍 查找问题就是在给定的集合(或者是多重集,它允许多个元素具有相同的值)中找寻一个给定的值,我们称之为查找键.有许多查找算法可供选择,其中既包括直截了当的顺序搜索,也包括效率极高但应用受限的折半查找,还有那些将原集合用另一种形式表示以方便查找的算法.最后一类算法对于现实应用具有特别重要的价值,因为它们对于大型数据库的信息存取来说是不可或缺的. 对于查找来说,没有一种算法在任何情况下都是最优的.有些算法速度比其他算法快,但需要较多的存储空间:有些算法速度非常快,但仅适用于有序

K-means聚类算法的三种改进(K-means++,ISODATA,Kernel K-means)介绍与对比

  一.概述 在本篇文章中将对四种聚类算法(K-means,K-means++,ISODATA和Kernel K-means)进行详细介绍,并利用数据集来真实地反映这四种算法之间的区别. 首先需要明确的是上述四种算法都属于"硬聚类"算法,即数据集中每一个样本都是被100%确定得分到某一个类别中.与之相对的"软聚类"可以理解为每个样本是以一定的概率被分到某一个类别中. 先简要阐述下上述四种算法之间的关系,已经了解过经典K-means算法的读者应该会有所体会.没有了解过

Android APP代码拨打电话、打开手机分享功能等隐式意图

Android APP拨打电话: Intent intent=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+110)); startActivity(intent); } Android APP打开电话薄: Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI); startActivity(intent); Android

数组中唯一出现一次的一个,两个,三个数,其余数都是偶数次出现(java版本)

首先在leetcode上面有这样类似的题,做法大致类似 1,首先是只出现一次的一个数 比较简单,直接全部亦或值就得到了 //只出现一次的一个数 public static int singleNumber1(int[] A) { int res=0; for(int i=0;i<A.length;i++) res^=A[i]; return res; } 2,只出现一次的两个数 则所有的值亦或肯定不为0,设最后的抑或结果为M,找到M从低到高为最先为1的位置,然后根据所有数在该位置为0或者1,分为