I want to make a grid of elements with a separator with fixed width of 1 "pixel". Like in a Photo
app grid for iOS.
For item width in a FlatList I use flex
style, because I can not predict their width on different screens.
Code example: https://snack.expo.io/ryK_zPmEM
But on my iPhone 7 Plus
(real device) i have got this result:
The separator between the second and the third cell has a style marginLeft: 1
but looks wider than the other two separators.
And this is a screenshot of the simulator for iPhone 5S
:
The result is the opposite. You can also notice that the thickness of the separator between the rows is also different.
The question is: what value should be set for margin
style so that separator looked the same for all screen sizes and did not change its width between the cells int the row?
Or perhaps I need to calculate the exact value for the width of the cell instead of using flex: 1
?
Full code example:
const WINDOW_WIDTH = Dimensions.get('window').width
const ITEMS_PER_ROW = 4
const MARGIN_WIDTH = 1
const TOTAL_MARGIN_WIDTH = MARGIN_WIDTH * (ITEMS_PER_ROW - 1)
const CELL_SIZE = (WINDOW_WIDTH - TOTAL_MARGIN_WIDTH) / ITEMS_PER_ROW
const listData = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
export default class App extends Component {
_renderItem = ({item, index}) => {
return (
<View style={[styles.cell, (index % 4 !== 0) ? styles.cellMargin : {}]}>
<Text>{item}</Text>
</View>
)
}
render() {
return (
<View style={styles.container}>
<FlatList
contentContainerStyle={styles.list}
columnWrapperStyle={styles.listColumn}
data={listData}
numColumns={ITEMS_PER_ROW}
keyExtractor={i => i}
renderItem={item => this._renderItem(item)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'red',
},
list: {
backgroundColor: 'cyan',
flex: 1,
},
listColumn: {
marginTop: 1,
height: CELL_SIZE,
backgroundColor: 'white',
},
cell: {
backgroundColor: 'green',
flex: 1,
},
cellMargin: {
marginLeft: MARGIN_WIDTH,
}
});