rikesan rikesan - 4 months ago 41
iOS Question

Continuously increasing counter with long press React Native

I have a button next to a

TextInput
that increases its counter when pressed.

<TouchableWithoutFeedback onPress={() => {this.increaseAmount(step, rowID)}}>
<View style={styles.amountPlusButtonContainer}>
<Text style={styles.amountButtonText}>+</Text>
</View>
</TouchableWithoutFeedback>


It currently increases by 1 each time I tap the button. What I want to achieve is to keep increasing the counter for as long as the user is pressing it.

I have tried to use
setInterval()
but I don't know exactly when to stop it nor if it's the right approach to this problem.

Answer

I was able to make it work using the Animated API. A reference I used (besides the official documentation) was http://browniefed.com/blog/react-native-press-and-hold-button-actions/

   var ACTION_TIMER = 3000;
   var listenerActive = true;

   getInitialState(){
     return{
       pressAction: new Animated.Value(0),
       value: 0,
     };
   },
   componentWillMount: function() {
     this.state.pressAction.addListener((v) => this.setState({value: v.value}));
   },
   handlePressIn: function() {
     if(!listenerActive) {
       this.state.pressAction.addListener((v) => this.setValueAndChangeAmount(v.value));
       listenerActive = true;
     }
     Animated.timing(this.state.pressAction, {
         duration: ACTION_TIMER,
         toValue: 67,
     }).start();
   },
   handlePressOut: function() {
     this.state.pressAction.removeAllListeners();
     this.setState({pressAction: new Animated.Value(Math.ceil(this.state.value))});
     listenerActive = false;
   },

I used 3000ms and Math.ceil to maintain the same behavior as onPress since it cannot be used alongside onPressInand onPressOut.

Removing the listener in handlePressOut stops the counter. Setting a new pressAction with this.state.value resets the value to the one the counter stopped at.