Skip to content

Instantly share code, notes, and snippets.

@machadogj
Created August 22, 2016 19:06
Show Gist options
  • Save machadogj/99409507362302f80a27599485a07fea to your computer and use it in GitHub Desktop.
Save machadogj/99409507362302f80a27599485a07fea to your computer and use it in GitHub Desktop.
Hacky way to scroll form on keyboard show.
componentWillUnmount() {
registerScrollViewForm.unregister(this.scrollviewForm);
}
_setFormScrollView(scrollView) {
this.scrollview = scrollviewForm;
registerScrollViewForm.register(scrollView);
}
render() {
return (
<ScrollView
contentContainerStyle={ styles.form }
ref={ this._setFormScrollView.bind(this) }
showsVerticalScrollIndicator
>
<MyForm...></MyForm>
);
}
import {
DeviceEventEmitter,
Platform,
TextInput
} from "react-native";
import { UIManager } from "NativeModules";
let _scrollViews = [];
function _keyboardWillShow(e) {
console.log('keyboard will show', e); //eslint-disable-line
let currentScrollview = _scrollViews.filter(s=>s.refs)[0];
if (!currentScrollview || !currentScrollview.refs.InnerScrollView) {
return;
}
console.log('scrollview found'); //eslint-disable-line
let currentTextInput = TextInput.State.currentlyFocusedField();
if (currentTextInput < 1) {
return;
}
console.log('text input found'); //eslint-disable-line
UIManager.measure(currentTextInput, (frameX, frameY, frameWidth, frameHeight, pageX, pageY) => { //eslint-disable-line
console.log("text input measure", frameX, frameY, frameWidth, frameHeight, pageX, pageY); //eslint-disable-line
if (pageY + frameHeight > e.endCoordinates.screenY) {
//the text input is being hidden by the keyboard.
currentScrollview.refs.InnerScrollView.measure((x, y, w, h, scrollPageX, scrollPageY)=> { //eslint-disable-line
console.log("scrollView measure", x, y, w, h, scrollPageX, scrollPageY); // eslint-disable-line
let relativeY = pageY - scrollPageY;
console.log("scrolling to:", relativeY - 30); //eslint-disable-line
currentScrollview.scrollTo(relativeY - 30);
});
}
else {
console.log('text input is not being hidden by the keyboard'); //eslint-disable-line
}
});
}
DeviceEventEmitter.addListener(Platform.OS === "IOS" ? "keyboardWillShow" : "keyboardDidShow", _keyboardWillShow);
function register(scrollView) {
if (scrollView === null) {
console.log("trying to register a null scrollView"); //eslint-disable-line
return;
}
_scrollViews.push(scrollView);
}
function unregister(scrollView) {
let index = _scrollViews.indexOf(scrollView);
if (index > -1) {
_scrollViews.splice(index, 1);
}
}
export default {
register,
unregister
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment