2

Tengo una aplicación en la que hay una vista con dos CardViews cada una de las cuales me dirigen a diferentes pantallas.

Ahora agregué otro CardView y ya hay tres. El problema es que ni en iOS ni en Android se muestra el tercio del CardView completo, solo se muestra una parte como muestro en la captura de pantalla.

Probé ScrollView ya que es una lista de pocos elementos y Scroll funciona, pero no se detiene y cuando suelto el dedo de la pantalla, la pantalla vuelve a su posición inicial ocultando el tercero de los CardView . Además, el desplazamiento cubre toda la pantalla, incluido el encabezado, que no debería ser el caso.También he intentado usar FlatList, pero obtengo errores.

He jugado con los estilos de View, pero no entiendo el problema que se ofrece para que el Scroll no funcione dentro de la View. He colocado flex : 1 a los CardView

Muestro el código del archivo, con el tercero del CardView agregado.

¿ Cómo puedo corregir esto y hacer que la pantalla se desplace para poder acceder a todos los CardView en la pantalla?

introducir la descripción de la imagen aquí

import React, { Component } from "react"
import _ from "lodash"
import ToolBar from "../../../component/ToolBar"
import styleApp from "../../../../res/style/style"
import AppText from "../../../component/Text"
import { strings } from "../../../config/i18n/i18n"
import CardView from "../../../component/CardView"

import { sizeWidth } from "../../../util/Size"
import NavigationActions from "../../../router/NavigationActions"
import {
  AsyncStorage,
  Image,
  StyleSheet,
  View,
  FlatList,
  ScrollView,
  List,
  SectionList
} from "react-native"

export default class PaintScreen extends Component {
  state = {
    isLoading: true,
    studiedAlphabet: [],
    studiedNumber: []
  };

  componentDidMount() {
    AsyncStorage.getAllKeys((error, keys) => {
      AsyncStorage.multiGet(keys, (error, stores) => {
        const alphabets = []
        const numbers = []
        stores.map((result, i, store) => {
          // get at each store's key/value so you can work with it
          if (store[i] != null) {
            //data provide is [key: value] - value [[]]
            if (store[i][0] == "learned_alphabets") {
              alphabets.push(JSON.parse(store[i][1]));
            }

            if (store[i][0] == "learned_numbers") {
              numbers.push(JSON.parse(store[i][1]));
            }
          }
          if (i == keys.length - 1) {
            this.setState({
              isLoading: false,
              studiedAlphabet: alphabets[0],
              studiedNumber: numbers[0]
            });
          }
        });
      });
    });
  }

  render() {
    if (!this.state.isLoading) {
      return (

        <View style={styles.containerMio}>

          <Image
            style={styles.backgroundImage}
            source={require("../../../../res/images_paint/background/backgroundA_2x.png")}
          />
          <Image
            style={styles.newPaintImage}
            source={require("../../../../res/images_paint/mainScreen/new_paint_ball_2x.png")}
          />

          {this.renderToolbar()}

          <View
            style={{
              width: "100%",
              alignItems: "center",
              position: "absolute",
              top: sizeWidth(20)
            }}
          >

            {this.renderAnimal()}
            {this.renderObject()}
            {this.renderAnimal()}

          </View>
    
        </View>

      )
    } else {
      return null
    }
  }

  renderToolbar = () => {
    return (
      <ToolBar
        center={
          <AppText style={styleApp.ToolBarText}>
            {strings("paint.title")}
          </AppText>
        }
      />
    );
  };

  renderAnimal = () => {
    return (
      <CardView
      style={{flex: 1}}
        image={require("../../../../res/images_paint/newPaintingScreen/animals_2x.png")}
        styleImg={styles.styleAnimal}
        title={strings("paint.animals")}
        backgroundColor={"#fff989"}
        colorButton={"#FE6230"}
        onPress={() =>
          NavigationActions.navigate("PaintAnimals", {
            studiedNumber: this.state.studiedNumber,
            studiedAlphabet: this.state.studiedAlphabet
          })
        }
      />
    );
  }

  renderObject = () => {
    const { studiedAlphabet } = this.state;


    return (
      <CardView
        style={{flex: 1}}
        image={require("../../../../res/images_paint/newPaintingScreen/object_2x.png")}
        styleImg={styles.styleObject}
        title={strings("paint.objects")}
        backgroundColor={"#B29FFF"}
        colorButton={"#FE6230"}
        onPress={() =>
          NavigationActions.navigate("PaintObjects", {
            studiedNumber: this.state.studiedNumber,
            studiedAlphabet: this.state.studiedAlphabet
          })
        }
      />
    )
  }

  renderAnimal = () => {
    return (
      <CardView
      style={{flex: 1}}
        image={require("../../../../res/images_paint/newPaintingScreen/animals_2x.png")}
        styleImg={styles.styleAnimal}
        title={strings("paint.animals")}
        backgroundColor={"#fff989"}
        colorButton={"#FE6230"}
        onPress={() =>
          NavigationActions.navigate("PaintAnimals", {
            studiedNumber: this.state.studiedNumber,
            studiedAlphabet: this.state.studiedAlphabet
          })
        }
      />
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column'
  },

  containerMio: {
    flex: 1,
    flexDirection: "column"
  },
  backgroundImage: {
    resizeMode: "stretch",
    position: "absolute",
    width: "100%",
    height: "100%"
  },
  newPaintImage: {
    position: "absolute",
    width: "100%",
    height: "100%"
  },
  styleAnimal: {
    flex: 1,
    resizeMode: "center",
    width: sizeWidth(70),
    height: sizeWidth(50),
    marginLeft: sizeWidth(-5),
  },
  styleObject: {
    flex: 1,
    resizeMode: "center",
    width: sizeWidth(70),
    height: sizeWidth(50),
    marginLeft: sizeWidth(-5),
  }
})

1 respuesta 1

2

El detalle que mencionas donde la pantalla se regresa a la posición inicial al soltar el dedo, se debe a que tal vez usaste {flex: 1} en contentContainerStyle para el componente ScrollView.

Te dejo un ejemplo rápido que podría ayudarte

export default class PaintScreen extends Component {
  // state...
  // componentDidMount...
  
  renderToolbar = () => {
   return <Text>Ejemplo de encabezado</Text>;
  };
  
  // Ejemplo de CardView
  renderCardView = () => {
   return (
    <Image
     style={{height: 200, width: 300, margin: 8, resizeMode: 'cover'}}
      source={{
       uri:
         'https://cdn.pixabay.com/photo/2017/02/20/18/03/cat-2083492__480.jpg',
      }}
    />
   );
  };

  render() {
   return (
    <View style={styles.container}>
      {this.renderToolbar()}
      <ScrollView
        style={{flex: 1}}
        contentContainerStyle={styles.scrollContainer}>
         {this.renderCardView()}
         {this.renderCardView()}
         {this.renderCardView()}
         {this.renderCardView()}
      </ScrollView>
     </View>
    );
   }
 }

 const styles = StyleSheet.create({
  container: {
   flex: 1,
   padding: 8,
   backgroundColor: 'red',
  },
  scrollContainer: {
   alignItems: 'center',
   backgroundColor: 'blue',
  },
 });

style={{flex: 1}} indica que nuestro componente scrollView va a tomar todo el tamaño disponible de la pantalla, en este ejemplo, sería todo el espacio restante debajo del Toolbar.

contentContainerStyle={styles.scrollContainer} es para asignar el estilo al contenedor dentro de nuestro ScrollView. En este ejemplo estamos indicando que el contenedor del scrollView será azul y va a centrar todos sus elementos horizontalmente.

El View que tienes como contenedor para tus CardViews con position "absolute" no es necesario, el {flex: 1} en el CardView tampoco.

Espero que te sea de ayuda!

1
  • Gracias, modificando un poco su código, encontré la solución. Solo tuve que sustituir los {this.renderCardView()} por mis diferentes CardView Aún me queda mucho que aprender en React Native, busco cursos y tutoriales para estudiar, sigo buscando proyecto de código libre para practicar y aprender. Pero es difícil encontrar cosas en Español. Gracias
    – Diana
    el 18 sep. 2021 a las 10:47

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.