ReactNative 滑動字母選擇城市 以及搜索功能

先上效果圖

mark

遇到的問題

  • 右側字母選擇器 高度問題,
  • 右側字母選擇器 如何使用手勢檢測panresponse
  • 右側字母選擇器 計算高度如何判斷是觸摸到那個字母上的(思考 如果是==native應用是如何做的==…剛看過 native應用的城市列表也是通過計算每個字母的高度來檢測的)動態創建的控件

右邊滑動的原理: 通過onlayout計算每個字母高度

,然後加入數組 , 手指觸摸字母列表時 知道 觸摸的y座標

這樣再減去列表距離頂部的距離 就是字母列表的初始座標.根據

y座標和剛纔通過onlayout計算出的數組進行比對在那個區間則是

哪一個字母的item

mark

下面上代碼

/**
 * Created by liuml on 2017/10/5.
 */

import React, {Component} from 'react';
import {
    View,
    Image,
    TouchableOpacity,
    Modal,
    Text,
    StatusBar,
    ListView,
    Platform,
    Dimensions,
    StyleSheet,
    RefreshControl,
    Alert,
    TextInput,
    PanResponder
} from 'react-native';
import _ from 'lodash';
import NavigationBar from './compont/NavigationBar'

const {width, height} = Dimensions.get('window')
const SECTIONHEIGHT = 30, ROWHEIGHT = 40

//這是利用lodash的range和數組的map畫出26個英文字母


var Util = require('./util/util');//工具類
var ScreenUtil = require('./util/ScreenUtil');//工具類
let city = [];//城市的數組 裏面放的是對象
var totalheight = [];//每個字母對應的城市和字母的總高度  比如所有a字母中數據的高度
var lettersItemheight = [];//每個字母的y座標
var myLetters = [];//我的字母數組
var myDataBlob = {};//獲取到的數據
var lettersBottom = 10;//字母列表距離底部高度
var mySectionIDs = []; //組id
var myRowIDs = [];//組內
var cityData = [];//獲取到的數據
var totalNumber = 10;//總條數的數據
var searchHeight = 35;//搜索框高度
var searchHeightMargin = 2;//搜索框margin
var lettersHeight;//字母列表高度
var that ;
export default class CityList extends Component {


    constructor(props) {
        super(props);
        // 獲取組中數據
        var getSectionData = (myDataBlob, mySectionIDs) => {
            // console.log("組id mySectionIDs = " + mySectionIDs);
            // console.log(`組中數據 = ${myDataBlob[mySectionIDs]}`);
            return myDataBlob[mySectionIDs];
        };
        // 獲取行中的數據
        var getRowData = (myDataBlob, mySectionIDs, myRowIDs) => {
            // console.log(`行中數據 = ${myDataBlob[myRowIDs]}`);
            return myDataBlob[myRowIDs];
        };
        this.state = {
            dataSource: new ListView.DataSource({
                getSectionHeaderData: getSectionData,
                getRowData: getRowData,
                rowHasChanged: (row1, row2) => row1 !== row2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
            }),
            isLoading: true,
            lettersShow: true
        }
        that = this;
    }

    //加載數據
    loadData = () => {

        // var thiz = this;
        Util.post('http://ovji4jgcd.bkt.clouddn.com/Mycity.json', {},
            (ret) => {
                // console.log(ret);
                if (ret.resCode == 1 && ret.data.length > 0) {

                    cityData = ret.data;
                    // console.log(cityData);
                    totalNumber = ret.totalNumber;
                    //一系列的操作 遍歷數組
                    console.log("正確的總數據: " + cityData);
                    this.setData(cityData);
                }
            });


    }

    //設置數據
    setData = (cityData) => {
        for (let i = 0; i < cityData.length; i++) {
            var mysectionName = 'Section_' + i;
            let cityMode = cityData[i].data;
            let zimu = cityData[i].zimu;
            mySectionIDs.push(mysectionName)
            myRowIDs[i] = [];
            var innerLoop = cityData[i].data; //內循環中的城市
            myDataBlob[mysectionName] = zimu;//把字母放入總數據
            myLetters.push(zimu)//把字母放入用於右邊的字母列表
            for (let jj = 0; jj < innerLoop.length; jj++) {
                let rowName = i + '_' + jj;
                myRowIDs[i].push(rowName);
                myDataBlob[rowName] = innerLoop[jj];
            }
            //組的高度  +  上行的高度 * 有多少行
            var eachheight = SECTIONHEIGHT + ROWHEIGHT * cityMode.length
            totalheight.push(eachheight)
        }
        let size = myLetters.length;
        // console.log("字母數量" + size);
        // console.log("lettersHeight = " + lettersHeight);
        //關閉對話框 設置數據源
        // console.log("打印setstate===================")
        this.setState({
            dataSource: this.state.dataSource.cloneWithRowsAndSections(myDataBlob, mySectionIDs, myRowIDs),
            isLoading: false,
            lettersShow: true
        })
    }
    //更新數據
    updateData = (cityData) => {
        console.log("更新的數據: " + cityData);
        let myDataBlob = [], mySectionIDs = [], myRowIDs = [];
        for (let i = 0; i < cityData.length; i++) {
            let mysectionName = 'Section_' + i;
            // let cityMode = cityData[i].data;
            let zimu = cityData[i].zimu;
            mySectionIDs.push(mysectionName)
            myRowIDs[i] = [];
            let innerLoop = cityData[i].data; //內循環中的城市
            myDataBlob[mysectionName] = zimu;//把字母放入總數據
            // myLetters.push(zimu)//把字母放入用於右邊的字母列表

            for (let jj = 0; jj < innerLoop.length; jj++) {
                let rowName = i + '_' + jj;
                myRowIDs[i].push(rowName);
                myDataBlob[rowName] = innerLoop[jj];
            }
        }

        // console.log("打印setstate===================")
        this.setState({
            dataSource: this.state.dataSource.cloneWithRowsAndSections(myDataBlob, mySectionIDs, myRowIDs),
            isLoading: false,
            lettersShow: false
        })
    }

    //返回箭頭
    handleBack = () => {
        //把任務棧頂部的任務清除
        this.props.navigation.goBack();
    }


    //左邊的箭頭
    getNavLeftBtn = () => {
        return <View style={{flexDirection: 'row', alignItems: 'center'}}>
            <TouchableOpacity
                activeOpacity={0.7}
                onPress={this.handleBack}>
                <Image source={require('../res/image/ic_arrow_back_white_36pt.png')}
                       style={{width: 24, height: 24}}/>
            </TouchableOpacity>
        </View>;
    }


    //頁面渲染加載完調用加載數據
    componentDidMount() {
        this.loadData();
    }

    //設置行
    renderRow(rowData, rowId) {
        return (
            <TouchableOpacity
                key={rowId}
                style={{height: ROWHEIGHT, justifyContent: 'center', paddingLeft: 20, paddingRight: 30}}
                onPress={() => {
                    that.changedata(rowData)
                }}>
                <View style={styles.rowdata}><Text style={styles.rowdatatext}>{rowData}</Text></View>
            </TouchableOpacity>
        )
    }

    //設置組
    renderSectionHeader = (sectionData, sectionID) => {
        return (
            <View style={{height: SECTIONHEIGHT, justifyContent: 'center', paddingLeft: 5, backgroundColor: 'gray'}}>
                <Text style={{color: 'black', fontWeight: 'bold', marginLeft: 10}}>
                    {sectionData}
                    {/*{console.log(`sectionData = ${sectionData}`)}*/}
                </Text>
            </View>
        )
    }
    // render ringht index Letters 右邊的字母
    // onLayout 測量字母
    renderLetters(letter, index) {
        return (
            <TouchableOpacity
                onLayout={({nativeEvent: e}) => this.oneLetterLayout(e)}
                key={index} activeOpacity={0.7}
                onPressIn={() => {
                    this.scrollTo(index)
                }}>
                <View
                    style={styles.letter}>
                    <Text style={styles.letterText}>{letter}</Text>
                </View>
            </TouchableOpacity>
        )
    }


    //回調改變顯示的城市
    changedata = (cityname) => {
        const {navigation} = this.props;
        const {state, goBack} = navigation;
        console.log(state);
        console.log(cityname);
        state.params.callback(cityname)
        goBack();
    }

    //touch right indexLetters, scroll the left
    scrollTo = (index) => {
        let position = 0;

        for (let i = 0; i < index; i++) {
            position += totalheight[i]
        }
        this._listView.scrollTo({
            y: position, animated: true
        })
    }


    //搜索框高度
    searchLayout = (e) => {
        // console.log('searchLayout 高度' + e.layout.height);
    }
    //字母高度
    lettersLayout = (e) => {
        // console.log('lettersLayout 高度' + e.layout.height);
        // console.log('lettersLayout y座標' + e.layout.y);
        lettersHeight = height - searchHeight * 2 - searchHeightMargin * 2;
        // console.log('字母列表高度 = ' + lettersHeight);
        // console.log('height = ' + height);
    }
    //每個字母高度
    oneLetterLayout = (e) => {
        // console.log('lettersLayout 高度' + e.layout.height);
        // console.log('每個字母高度 y座標' + e.layout.y);
        // if (lettersItemheight.length >= 0) {
        //     lettersItemheight = [];
        // }
        if (lettersItemheight.length != myLetters.length) {
            lettersItemheight.push(e.layout.y);
        }
    }
    //文本改變
    changeText = (text) => {
        // console.log("改變的文本: " + text);
        text = text.trim();
        if (text != "") {
            if (/^[\u4e00-\u9fa5]/.test(text)) {//是否有中文
                console.log("===有中文===")
                let mCityData = [];
                console.log("原始數據: " + cityData);
                let k = 0;
                for (let i = 0; i < cityData.length; i++) {
                    let data = [];
                    data = cityData[i].data;
                    // console.log("data = " + data);
                    // console.log("data 長度 = " + data.length);
                    let isHas = false;//是否存在

                    var itemData = [];//這裏是匹配的城市數據
                    for (let j = 0; j < data.length; j++) {
                        // console.log("字符串是否相等"+data[j].includes(text));
                        // console.log("輸入框內: "+text);
                        // console.log("數據內: "+data[j]);

                        // itemData = cityData[i];
                        if (data[j].includes(text)) {
                            console.log("正確的itm data = " + cityData[i].data);
                            itemData.push(data[j]);
                            // mCityData.push(data);
                            isHas = true;//
                        }
                    }
                    //內層循環結束
                    console.log("itemData = " + itemData);
                    if (isHas) {
                        let obj;
                        obj = {'zimu': cityData[i].zimu, 'data': itemData, 'id': cityData[i].id};
                        console.log("添加的數據 " + obj.zimu + " " + obj.data);
                        console.log("添加的數據 " + obj);
                        mCityData[k] = obj;
                        k++;
                    }



                }
                // console.log("過濾後的數據: " + mCityData[0].data);
                // console.log("過濾後的數據: " + mCityData[1].data);
                // console.log("過濾後的數據長度: " + mCityData.length);
                // console.log("過濾後的數據: "+mCityData );
                // mCityData.map((item, i) => {
                //     console.log("\n" + item.data);
                // })
                this.updateData(mCityData);

            } else {//否則是英文
                for (let i = 0; i < cityData.length; i++) {
                    console.log("===英文===")
                    // console.log("打印字母 " + cityData[i].zimu);
                    // console.log("打印改變的文字 " + text.toLowerCase());
                    if (cityData[i].zimu == text.toUpperCase()) {
                        // if (cityData[i].zimu.indexOf(text) != -1) {
                        let mCityData = [];
                        mCityData.push(cityData[i]);
                        this.updateData(mCityData);
                        return;
                    }
                }
            }
        } else {
            // myDataBlob.map((item ,i)=>{
            //     console.log(item);
            // })
            // console.log(myDataBlob);
            // console.log(mySectionIDs);
            // console.log(myRowIDs);
            //
            // console.log("打印setstate===================")
            console.log("===數據爲空刷新===")
            this.setState({
                dataSource: this.state.dataSource.cloneWithRowsAndSections(myDataBlob, mySectionIDs, myRowIDs),
                isLoading: false,
                lettersShow: true
            })
        }

    }

    componentWillMount() {
        this._panGesture = PanResponder.create({
            //要求成爲響應者:
            onStartShouldSetPanResponder: (evt, gestureState) => true,
            onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
            onMoveShouldSetPanResponder: (evt, gestureState) => true,
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
            onPanResponderTerminationRequest: (evt, gestureState) => true,

            onPanResponderGrant: (evt, gestureState) => {

                // console.log('觸摸 當響應器產生時的屏幕座標 \n x:' + gestureState.x0 + ',y:' + gestureState.y0);
                let value = gestureState.y0 - searchHeight * 2 - lettersBottom + 1;
                // console.log("點擊的點 : " + value);

                for (let i = 0; i < lettersItemheight.length; i++) {
                    if (value < 0) {
                        this.scrollTo(0);
                    } else if (value > lettersItemheight[i]) {
                        this.scrollTo(i);
                    }
                }
            },
            onPanResponderMove: (evt, gestureState) => {
                // console.log('移動 最近一次移動時的屏幕座標\n moveX:' + gestureState.moveX + ',moveY:' + gestureState.moveY);
                // console.log('移動 當響應器產生時的屏幕座標\n x0:' + gestureState.x0 + ',y0:' + gestureState.y0);
                // console.log('移動 從觸摸操作開始時的累計縱向路程\n dx:' + gestureState.dx + ',dy :' + gestureState.dy);

                let value = gestureState.moveY - searchHeight * 2 - lettersBottom + 1;
                // console.log("移動的點 " + value);

                for (let i = 0; i < lettersItemheight.length; i++) {
                    if (value < 0) {
                        this.scrollTo(0);
                    } else if (value > lettersItemheight[i]) {
                        this.scrollTo(i);
                    }
                }

                // console.log(this.mul(sub, myLetters.length));
            },
            onResponderTerminationRequest: (evt, gestureState) => true,
            onPanResponderRelease: (evt, gestureState) => {
                // console.log('擡手 x:' + gestureState.moveX + ',y:' + gestureState.moveY);
            },
            onPanResponderTerminate: (evt, gestureState) => {
                // console.log(`結束 = evt.identifier = ${evt.identifier} gestureState = ${gestureState}`);
            },
        });

    }

    //做一些清除操作 避免再次進入會有數據異常
    componentWillUnmount() {
        myLetters = [];
        myDataBlob = {};//獲取到的數據
        mySectionIDs = []; //組id
        myRowIDs = [];//組內
        cityData = [];//獲取到的數據
        lettersItemheight = [];
    }


    //渲染
    render() {
        return (
            <View style={styles.container}>
                <NavigationBar
                    onLayout={({nativeEvent: e1}) => this.navigationLayout(e1)}
                    ref={(ref) => this.myNavigationBar = ref}
                    title="選擇城市"
                    leftButton={this.getNavLeftBtn()}
                ></NavigationBar>

                <View

                    onLayout={({nativeEvent: e}) => this.searchLayout(e)}
                    style={styles.searchBox}>
                    <Image source={require('../res/image/search_bar_icon_normal.png')} style={styles.searchIcon}/>
                    <TextInput style={styles.inputText}
                               onChangeText={(text) => this.changeText(text)}
                               underlineColorAndroid='transparent' //設置下劃線背景色透明 達到去掉下劃線的效果
                               placeholder='請輸入城市名稱或首字母'/>
                </View>
                <ListView
                    contentContainerStyle={styles.contentContainer}
                    ref={listView => this._listView = listView}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow}
                    renderSectionHeader={this.renderSectionHeader}
                    enableEmptySections={true}
                    initialListSize={totalNumber}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isLoading}
                            tintColor="#63B8FF"
                            title="正在加載..."
                            titleColor="#63B8FF"
                            colors={['#63B8FF']}
                        />
                    }
                />
                {
                    //判斷是否顯示右邊字母列表
                    this.state.lettersShow == false ? (null) :
                        (   <View
                                ref="ref_letters"
                                {...this._panGesture.panHandlers}
                                onLayout={({nativeEvent: e}) => this.lettersLayout(e)}
                                style={styles.letters}>
                                {myLetters.map((letter, index) => this.renderLetters(letter, index))}
                            </View>
                        )
                }
            </View>
        );
    }
};
const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column'
    },
    contentContainer: {
        width: width,
        paddingBottom: 20,
        backgroundColor: 'white',
    },
    //字母列表的樣式
    letters: {
        flexDirection: 'column',
        position: 'absolute',
        height: height - searchHeight - searchHeight - lettersBottom - StatusBar.currentHeight,
        top: searchHeight + searchHeight + 4,
        bottom: lettersBottom,
        right: 10,
        backgroundColor: 'transparent',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    // height 字母的高度間距
    // width 字母的寬度
    letter: {
        height: height * 3.3 / 100,
        width: width * 3 / 50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    letterText: {//右邊list字母的樣式
        textAlign: 'center',
        fontSize: height * 1.1 / 50,
        color: 'black'
    },
    rowdata: {//下劃線的樣式
        borderBottomColor: '#faf0e6',
        borderBottomWidth: 0.5
    },
    rowdatatext: {
        color: 'gray',
    },
    searchBox: {//最外層搜索框包裹
        height: searchHeight,
        borderColor: 'black',
        flexDirection: 'row',   // 水平排布
        borderRadius: 10,  // 設置圓角邊
        backgroundColor: '#FFF',
        borderWidth: 0.8,
        borderRadius: 10,
        borderColor: 'gray',
        alignItems: 'center',
        marginLeft: 8,
        paddingTop: 0,
        marginTop: searchHeightMargin,
        marginBottom: searchHeightMargin,
        paddingBottom: 0,
        marginRight: 8,

    },
    searchIcon: {//搜索圖標
        height: 20,
        width: 20,
        marginLeft: 5,
        resizeMode: 'stretch'
    },
    inputText: {//搜索框
        backgroundColor: 'transparent',
        fontSize: 13,
        paddingBottom: 0,
        paddingTop: 0,
        flex: 1,
    },

})

Github 地址

右上角點擊一下star 就是對我最好的支持 也是我的動力 謝謝

https://github.com/liudao01/cityList

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章