class ChaMenu < UIView attr_accessor :delegate, :data, :selected_index, :scroll_view attr_accessor :font_size, :normal_color, :selected_color, :highlight_color attr_accessor :background_color attr_accessor :selected_index def setup self.autoresizingMask = UIViewAutoresizingFlexibleWidth @font_size ||= 16 @normal_color ||= UIColor.blackColor @highlight_color||= UIColor.grayColor @selected_color ||= UIColor.blueColor @selected_index ||= 0 @scroll_view = UIScrollView.alloc.initWithFrame(self.bounds) @scroll_view.backgroundColor = @background_color || UIColor.whiteColor @scroll_view.autoresizingMask = UIViewAutoresizingFlexibleWidth @scroll_view.showsVerticalScrollIndicator = false @scroll_view.showsHorizontalScrollIndicator = false @scroll_view.delegate = self self.addSubview @scroll_view reload_data end def set_select_index(index) return if @selected_index == index @selected_index = index end def reload_data @scroll_view.subviews.each {|v| v.removeFromSuperview } x = 0 padding = 10 selected_frame = [[0,0], [0,0]] @data.each_with_index do |text, index| x += padding font = UIFont.systemFontOfSize(@font_size) size = text.sizeWithFont(font, constrainedToSize:[10000, 300], lineBreakMode:NSLineBreakByCharWrapping) frame = [[x, padding], [size.width, size.height]] selected_frame = frame if index == @selected_index @scroll_view.addSubview menu_button(text, index, frame) x += size.width end content_width = x + padding @scroll_view.setContentSize([content_width, @scroll_view.frame.size.height]) if @selected_index > 0 @scroll_view.scrollRectToVisibleCenteredOn(selected_frame, animated:false) end end def menu_button(text, index, frame) button = UIButton.alloc.initWithFrame(frame) button.titleLabel.textAlignment = UITextAlignmentCenter button.titleLabel.font = UIFont.systemFontOfSize(@font_size) button.setTitle(text, forState:UIControlStateNormal) if index == @selected_index button.setTitleColor(@selected_color, forState:UIControlStateNormal) else button.setTitleColor(@normal_color, forState:UIControlStateNormal) end button.setTitleColor(@highlight_color, forState:UIControlStateHighlighted) #button.setTitleColor(@selected_color, forState:UIControlStateSelected) button.addTarget(self, action: 'menu_select:', forControlEvents:UIControlEventTouchUpInside) button.tag = index button end def menu_select(sender) UIView.animateWithDuration(0.2, delay:0, options:UIViewAnimationOptionCurveLinear, animations: -> { @scroll_view.scrollRectToVisibleCenteredOn(sender.frame, animated:false) }, completion:nil) @selected_index = sender.tag reload_data if @delegate.respond_to?(:selected_menu) @delegate.selected_menu(@selected_index) else NSLog("Warning: Did not find selected_menu method.") end end def delegate=(parent) @delegate = WeakRef.new(parent) end def scrollViewDidScroll(scrollView) end end