4 ms·
Shorter than the React code, I'm not seeing a big win other than the need for an explicit render() in didSet, which also allows for more fine-grained control if
by mjmsmith 9y ago
Shorter than the React code, I'm not seeing a big win other than the need for an explicit render() in didSet, which also allows for more fine-grained control if needed.
class ViewController: UIViewController {
let indicatorView = ConnectivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
indicatorView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 20, height: 20))
view.addSubview(indicatorView)
}
}
class ConnectivityIndicatorView: UIView {
var isConnected: Bool = false {
didSet {
render()
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
isConnected = arc4random()%10 > 4
}
func render() {
backgroundColor = isConnected ? .green : .red
}
}
- gunn 9y agoHere's a more canonical version of the exact same logic in react: const Root = ()=> <ConnectivityIndicatorView/> class ConnectivityIndicatorView extends Component { state = { isConnected: false } componentDidMount() { const isConnected = Math.random() > 0.5 this.setState({ isConnected }) } render() { const backgroundColor = this.state.isConnected ? 'green' : 'red' return <View style={{backgroundColor, width: 20, height: 20}}/> } } And here's how I would actually write it in my own app: const Root = ()=> <ConnectivityIndicatorView isConnected={Math.random() > 0.5}/> const ConnectivityIndicatorView = ({isConnected})=> { const backgroundColor = isConnected ? 'green' : 'red' return <View style={{backgroundColor, width: 20, height: 20}}/> }