Module: ChaWork::Basic

Defined in:
lib/cha_work/basic.rb

Instance Method Summary collapse

Instance Method Details

#action_item(action_name) ⇒ Object



346
347
348
349
350
351
352
# File 'lib/cha_work/basic.rb', line 346

def action_item(action_name)
  item = UIBarButtonItem.alloc.
    initWithBarButtonSystemItem(UIBarButtonSystemItemAction,
                                target:self,
                                action:action_name)
  item
end

#add_item(action_name) ⇒ Object

系统add按扭



390
391
392
393
394
395
396
# File 'lib/cha_work/basic.rb', line 390

def add_item(action_name)
  item = UIBarButtonItem.alloc.
    initWithBarButtonSystemItem(UIBarButtonSystemItemAdd,
                                target:self,
                                action:action_name)
  item
end

#add_subviews(view, objs) ⇒ Object



433
434
435
436
# File 'lib/cha_work/basic.rb', line 433

def add_subviews(view, objs)
  objs.each { |obj| view.addSubview(obj) if !obj.nil? }
  view
end

#alert(title, args = {}) ⇒ Object

Displays a UIAlertView.

title - The title as a String. args - The title of the cancel button as a String, or a Hash of options.

(Default: { cancel_button_title: 'OK' })
cancel_button_title - The title of the cancel button as a String.
message             - The main message as a String.

block - Yields the alert object if a block is given, and does so before the alert is shown.

Returns an instance of BW::UIAlertView



544
545
546
547
548
549
550
551
552
553
# File 'lib/cha_work/basic.rb', line 544

def alert(title, args={})
  alert = UIAlertView.alloc.initWithTitle(title, 
                  message:'',
                 delegate:self,
        cancelButtonTitle:"确定",
        otherButtonTitles:nil)

  alert.show
  alert
end

#bar_item(title, action_name) ⇒ Object



334
335
336
337
338
339
340
# File 'lib/cha_work/basic.rb', line 334

def bar_item(title, action_name)
  item = UIBarButtonItem.alloc.initWithTitle(title,
                                             style:UIBarButtonItemStyleBordered,
                                             target:self,
                                             action:action_name)
  item
end

#bbutton(text, frame, type = :info, action = nil) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/cha_work/basic.rb', line 206

def bbutton(text, frame, type=:info, action=nil)
  frame = get_frame(frame)
  symbol  = {info:    BButtonTypeInfo, 
            success: BButtonTypeSuccess, 
            danger:  BButtonTypeDanger,
            default: BButtonTypeDefault,
            primary: BButtonTypePrimary,
            warning: BButtonTypeWarning}
  type    = symbol[type] || BButtonTypeInfo
  btn = BButton.alloc.initWithFrame(frame, type:type, style:BButtonStyleBootstrapV3)
  btn.setTitle(text, forState:UIControlStateNormal)
  btn.on(:touch) { send(action) } if action
  btn
end

#bottom_line(frame, color = '#ECECEC') ⇒ Object



87
88
89
90
91
92
93
# File 'lib/cha_work/basic.rb', line 87

def bottom_line(frame, color='#ECECEC')
  frame     = get_frame(frame)
  new_frame = [[frame[0][0], frame[0][1] + frame[1][1] - 0.5], [frame[1][0], 0.5]]
  bg = create_view(new_frame, color, 1)
  bg.autoresizingMask = UIViewAutoresizingFlexibleTopMargin
  bg
end

#button(text, frame, size = 16, color = '#1D92B5', action = nil, param = nil, align = nil, bold = false) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/cha_work/basic.rb', line 167

def button(text, frame, size=16, color='#1D92B5', action=nil, param=nil, align=nil, bold=false)
  size  ||= 16
  color ||= '#1D92B5'
  frame = get_frame(frame)

  button                 = UIButton.alloc.initWithFrame(frame)
  button.titleLabel.font = bold ? UIFont.boldSystemFontOfSize(size) : UIFont.systemFontOfSize(size)
  button.setTitle(text, forState:UIControlStateNormal)
  button.setTitleColor(color.uicolor, forState:UIControlStateNormal)
  # button.setTitleColor(:darkgray.uicolor, forState:UIControlStateHighlighted)

  case align
  when nil, :center, 'center'
    button.setContentHorizontalAlignment(UIControlContentHorizontalAlignmentCenter)
  when :right,  'right'
    button.setContentHorizontalAlignment(UIControlContentHorizontalAlignmentRight)
  when :left, 'left'
    button.setContentHorizontalAlignment(UIControlContentHorizontalAlignmentLeft)
  end


  case action
  when 'back' then button.on(:touch) { pop }
  when 'hide' then button.on(:touch) { hide }
  when 'user' then button.on(:touch) { push UserDetail.alloc.initWithId(param) } # TODO: Decouple UserDetail
  else
    unless action.nil?
      if param.nil?
        button.on(:touch) { send(action) }
      else
        button.on(:touch) { send(action, param) }
      end
    end
  end

  button
end

#change_btn_image(btn, name) ⇒ Object



221
222
223
# File 'lib/cha_work/basic.rb', line 221

def change_btn_image(btn, name)
  btn.setImage(name.uiimage, forState:UIControlStateNormal)
end

#context(text, frame, font_size = 16, color = '#000000', absolute = false, align = nil, length = nil) ⇒ Object

自适应高度label



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/cha_work/basic.rb', line 137

def context(text, frame, font_size = 16, color='#000000', absolute=false, align=nil, length=nil)
  frame = get_frame(frame)
  color     ||= '#000000'
  font_size ||= 16
  lbl                 = UILabel.new
  lbl.backgroundColor = UIColor.clearColor
  lbl.textColor       = color.uicolor

  font      = UIFont.systemFontOfSize(font_size)
  width     = frame[1][0]
  
  if absolute
    lbl.frame = frame
  else
    lbl.frame = CGRectMake(frame[0][0], frame[0][1], width, text.height(width: width, size: font_size))
  end

  case align
  when nil, :left, 'left' then lbl.textAlignment = NSTextAlignmentLeft
  when :right,  'right'   then lbl.textAlignment = NSTextAlignmentRight
  when :center, 'center'  then lbl.textAlignment = NSTextAlignmentCenter
  end

  lbl.font = font
  lbl.numberOfLines = 0
  lbl.lineBreakMode = NSLineBreakByWordWrapping
  lbl.text   = text
  lbl
end

#create_view(frame, color = '#FFFFFF', opacity = 1, shadow = false) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/cha_work/basic.rb', line 72

def create_view(frame, color='#FFFFFF', opacity=1, shadow=false)
  frame = get_frame(frame)
  view = UIView.alloc.initWithFrame(frame)
  opacity = 1 if opacity.nil?
  view.backgroundColor = "#{color}".uicolor.colorWithAlphaComponent(opacity)
  if shadow
    #view.layer.masksToBounds = NO
    #view.layer.cornerRadius = 8
    view.layer.shadowOffset = CGSizeMake(1, 2)
    view.layer.shadowRadius = 1
    view.layer.shadowOpacity = 0.3
  end
  view
end

#custom_item(view) ⇒ Object



330
331
332
# File 'lib/cha_work/basic.rb', line 330

def custom_item(view)
  UIBarButtonItem.alloc.initWithCustomView(view)
end

#empty_cellObject



504
505
506
507
508
509
510
# File 'lib/cha_work/basic.rb', line 504

def empty_cell
  cell = UITableViewCell.alloc.init
  cell.contentView.subviews.each do |subview|
    subview.removeFromSuperview
  end
  cell
end


95
96
97
98
99
# File 'lib/cha_work/basic.rb', line 95

def footer(color='#FFFFFF')
  view = UIView.alloc.init
  view.backgroundColor = color.uicolor
  view
end

#friendly_time(from_time, include_seconds = false) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/cha_work/basic.rb', line 466

def friendly_time(from_time, include_seconds = false)
  if from_time.class == Bignum
    time_value = from_time - Time.now.to_i
  else
    time_value = from_time - Time.now
  end
  distance_in_minutes = (((time_value).abs)/60).round
  distance_in_seconds = ((time_value).abs).round

  case distance_in_minutes
  when 0..1
    return (distance_in_minutes == 0) ? '不到1分钟' : '1分钟' unless include_seconds
    case distance_in_seconds
    when 0..4   then '刚刚'
    when 5..9   then '10秒前'
    when 10..19 then '20秒前'
    when 20..39 then '半分钟前'
    when 40..59 then '不到1分钟'
    else             '1分钟'
    end

  when 2..44           then "#{distance_in_minutes}分钟前"
  when 45..89          then '1小时前'
  when 90..1439        then "#{(distance_in_minutes.to_f / 60.0).round} 小时前"
  when 1440..2879      then '1天前'
  when 2880..43199     then "#{(distance_in_minutes / 1440).round}天前"
  when 43200..86399    then '1个月前'
  when 86400..525599   then "#{(distance_in_minutes / 43200).round}个月"
  when 525600..1051199 then '1年左右'
  else                      "#{(distance_in_minutes / 525600).round}"
  end
end

#full_view(color = '#FFFFFF', opacity = 1) ⇒ Object



65
66
67
68
69
70
# File 'lib/cha_work/basic.rb', line 65

def full_view(color='#FFFFFF', opacity=1)
  frame = [[0,0], [UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height]] 
  view  = UIView.alloc.initWithFrame(frame)
  view.backgroundColor = "#{color}".uicolor.colorWithAlphaComponent(opacity)
  view
end

#get_frame(str) ⇒ Object Also known as: _

‘0,0,0,0’ = ‘x,y,w,h’, 若x为负数则表示向右对齐, 若为负数,则表示view.height - 数值



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/cha_work/basic.rb', line 34

def get_frame(str)
  if str.nil?
    warn('frame为nil')
    return [[0,0],[0,0]]
  end

  return str if str.class == Array

  frame = str.split(',')

  x = get_value(frame[0]) 
  y = get_value(frame[1])
  width = get_value(frame[2])
  height= get_value(frame[3])
  [[x, y], [width, height]]
end

#get_value(val) ⇒ Object

格式,100/80, /号前是4寸屏值,/号后是3.5寸屏值



52
53
54
55
56
57
58
59
60
61
# File 'lib/cha_work/basic.rb', line 52

def get_value(val)
  if val.nil?
    NSLog("frame error, missing")
    return 0 
  end
  array = val.split("/")
  # 若只有一个值,直接返回
  return val.to_i if array.length == 1 
  return UIScreen.mainScreen.bounds.size.height > 480 ? array[0].to_i : array[1].to_i
end

#hide(bool = true) ⇒ Object



19
20
21
# File 'lib/cha_work/basic.rb', line 19

def hide(bool=true)
  self.dismissModalViewControllerAnimated(bool)
end

#image(url, frame, placeholder = 'photo', round = false, fit = false) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/cha_work/basic.rb', line 252

def image(url, frame, placeholder='photo', round=false, fit=false)
  placeholder ||= 'photo'

  frame = get_frame(frame)
  image_view = UIImageView.alloc.initWithFrame frame

  if url.nil? || url == ''
    image_view.image = placeholder.uiimage
  elsif url.class == UIImage
    image_view.image = url
  elsif url.downcase.include? 'http'
    image_view.setImageWithURL(url.nsurl, placehoderImage:placeholder.uiimage)

    if fit
      image_view.contentMode   = UIViewContentModeScaleAspectFill
      image_view.clipsToBounds = true

      # image_view.setImageWithURL(url.nsurl,
      #                     success:-> image, cached do
      #                        ratio = image.size.width / 320
      #                        height= 200 #frame[1][1]
      #                        rect = [[0, 0], [image.size.width, height * ratio]]
      #                        imageRef = CGImageCreateWithImageInRect(image.CGImage, rect)
      #                        img = UIImage.imageWithCGImage imageRef
      #                        CGImageRelease(imageRef)
      #                        image_view.image = img
      #                     end, failure:nil)

    end

    # warn("1:#{url}")
  elsif url.class == String
    
    image_view.image = url.uiimage

  else
    image_view.image = placeholder.uiimage
  end

  if round
    image_view.layer.cornerRadius   = frame[1][1] / 2
    image_view.layer.masksToBounds  = true
  end
  image_view
end

#image_btn(name, frame, action = nil, param = nil) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/cha_work/basic.rb', line 225

def image_btn(name, frame, action=nil, param=nil)
  frame = get_frame(frame)
  button = UIButton.alloc.initWithFrame frame
  if name.include? ','
    val = name.split(",")
    button.setImage(val[0].uiimage, forState:UIControlStateNormal)
    button.setImage(val[1].uiimage, forState:UIControlStateHighlighted)
  else
    button.setImage(name.uiimage, forState:UIControlStateNormal)
  end

  case action
  when 'back' then button.on(:touch) { pop }
  when 'hide' then button.on(:touch) { hide }
  else
    unless action.nil?
      if param.nil?
        button.on(:touch) { send(action) }
      else
        button.on(:touch) { send(action, param, button) }
      end
    end
  end

  button
end

#image_item(image_name, action_name) ⇒ Object



342
343
344
# File 'lib/cha_work/basic.rb', line 342

def image_item(image_name, action_name)
  UIBarButtonItem.alloc.initWithImage(image_name.uiimage, style: UIBarButtonItemStyleBordered, target: self, action: action_name)
end

#label(text, frame, size = 16, bold = false, color = '#000000', align = nil, background = nil, shadow = false, shadow_color = '#CCCCCC') ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/cha_work/basic.rb', line 101

def label(text, frame, size=16, bold=false, color='#000000', align=nil, background=nil, shadow=false, shadow_color='#CCCCCC')
  frame                    = get_frame(frame)
  lbl 			               = UILabel.alloc.initWithFrame(frame)
  lbl.text                 = text.to_s
  
  if background.nil?
    lbl.backgroundColor = UIColor.clearColor
  else
    lbl.backgroundColor = "#{background}".uicolor
  end

  lbl.highlightedTextColor = :white.uicolor

  lbl.textColor       = color.uicolor unless color.nil?
  font_size           = size.nil? ? 16 : size
  lbl.font 		        = bold ? UIFont.boldSystemFontOfSize(font_size) :
    UIFont.systemFontOfSize(font_size)

  case align
  when nil, :left, 'left'
    lbl.textAlignment   = UITextAlignmentLeft
  when :right,  'right'
    lbl.textAlignment   = UITextAlignmentRight
  when :center, 'center'
    lbl.textAlignment   = UITextAlignmentCenter
  end

  if shadow
    shadow_color      = '#CCCCCC' if shadow_color.nil?
    lbl.shadowColor   = shadow_color.uicolor
    lbl.shadowOffset  = CGSizeMake(0, 1)
  end
  lbl
end

#loading_view(height = nil) ⇒ Object



512
513
514
515
516
517
518
519
520
521
522
# File 'lib/cha_work/basic.rb', line 512

def loading_view(height=nil)
  height = height || self.view.frame.size.height
  bg     = create_view("0,0,320,#{height}", '#FFFFFF', 0)

  progressInd       = UIActivityIndicatorView.alloc.initWithActivityIndicatorStyle(UIActivityIndicatorViewStyleGray)
  bg.addSubview progressInd
  progressInd.center= [110, height/2]
  progressInd.startAnimating
  bg.addSubview label('请稍后...', [[130, height/2-7], [100,16]], 16, false, '#878787')
  bg
end

#log(msg) ⇒ Object



499
500
501
# File 'lib/cha_work/basic.rb', line 499

def log(msg)
  NSLog(msg)
end

#mainObject



4
5
6
# File 'lib/cha_work/basic.rb', line 4

def main
  UIApplication.sharedApplication.delegate
end

#map(location, frame, span = 0.1, type = 'standard', show_me = false) ⇒ Object



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/cha_work/basic.rb', line 311

def map(location ,frame, span=0.1, type='standard', show_me=false)
  map_view = MKMapView.alloc.initWithFrame(frame)
  map_view.mapType = (type == 'satellite') ? MKMapTypeSatellite : MKMapTypeStandard

  # 显示用户当前的坐标
  map_view.showsUserLocation=true if show_me
  region                     = MKCoordinateRegion.new
  region.center.latitude     = location[0]
  region.center.longitude    = location[1]

  span = 0.1 if span.nil?
  region.span.latitudeDelta  = span
  region.span.longitudeDelta = span
  map_view.region            = region
  map_view.autoresizingMask  = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight

  map_view
end

#open_url(url) ⇒ Object



525
526
527
528
529
530
# File 'lib/cha_work/basic.rb', line 525

def open_url(url)
  unless url.is_a?(NSURL)
    url = NSURL.URLWithString(url)
  end
  UIApplication.sharedApplication.openURL(url)
end

#password_field(frame, placeholder = '', text = '') ⇒ Object



429
430
431
# File 'lib/cha_work/basic.rb', line 429

def password_field(frame, placeholder='', text='')
  textfield(frame, placeholder.to_s, text.to_s, true)
end

#pop(bool = true) ⇒ Object



23
24
25
# File 'lib/cha_work/basic.rb', line 23

def pop(bool=true)
  self.navigationController.popViewControllerAnimated(bool)
end

#pop_to_root(bool = true) ⇒ Object



27
28
29
# File 'lib/cha_work/basic.rb', line 27

def pop_to_root(bool=true)
  self.navigationController.popToRootViewControllerAnimated(bool)
end

#push(view, bool = true, hide = true) ⇒ Object



8
9
10
11
# File 'lib/cha_work/basic.rb', line 8

def push(view, bool=true, hide=true)
  view.hidesBottomBarWhenPushed = hide
  self.navigationController.pushViewController(view, animated:bool)
end

#refresh_item(action_name) ⇒ Object

系统refresh按扭



399
400
401
402
403
404
405
# File 'lib/cha_work/basic.rb', line 399

def refresh_item(action_name)
  item = UIBarButtonItem.alloc.
    initWithBarButtonSystemItem(UIBarButtonSystemItemRefresh,
                                target:self,
                                action:action_name)
  item
end

#segment(frame, items, actions, default = 0, color = '#FF9900') ⇒ Object

生成segement



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/cha_work/basic.rb', line 445

def segment(frame, items, actions, default=0, color='#FF9900')

  items   = items.split(",")    
  actions = actions.split(",")

  #初始化UISegmentedControl  
  segmentedControl = UISegmentedControl.alloc.initWithItems(items)  
  segmentedControl.frame = get_frame(frame)
  segmentedControl.selectedSegmentIndex   = default
  segmentedControl.tintColor              = color.uicolor 
  segmentedControl.segmentedControlStyle  = UISegmentedControlStylePlain
  segmentedControl.on(:value_changed) do
    if actions.length >= segmentedControl.selectedSegmentIndex + 1
      action = actions[segmentedControl.selectedSegmentIndex]
      send(action)
    end
  end

  segmentedControl
end

#set_image(btn, name) ⇒ Object



438
439
440
441
# File 'lib/cha_work/basic.rb', line 438

def set_image(btn, name)
  btn.setImage(name.uiimage, forState:UIControlStateNormal)
  btn
end

#show(view, bool = true) ⇒ Object



13
14
15
16
17
# File 'lib/cha_work/basic.rb', line 13

def show(view, bool=true)
  # NOTE: -[UIViewController presentModalViewController] is deperated!
  self.presentViewController(view, animated:bool, completion: nil)
  # self.presentModalViewController(view, animated:true)
end

#system_item(symbol, action_name) ⇒ Object



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/cha_work/basic.rb', line 354

def system_item(symbol, action_name)
  name = {
    done:         UIBarButtonSystemItemDone,
    cancel:       UIBarButtonSystemItemCancel,
    edit:         UIBarButtonSystemItemEdit,
    save:         UIBarButtonSystemItemSave,
    add:          UIBarButtonSystemItemAdd,
    flexible_space: UIBarButtonSystemItemFlexibleSpace,
    fixed_space:    UIBarButtonSystemItemFixedSpace,
    compose:      UIBarButtonSystemItemCompose,
    reply:        UIBarButtonSystemItemReply,
    action:       UIBarButtonSystemItemAction,
    organize:     UIBarButtonSystemItemOrganize,
    bookmarks:    UIBarButtonSystemItemBookmarks,
    search:       UIBarButtonSystemItemSearch,
    refresh:      UIBarButtonSystemItemRefresh,
    stop:         UIBarButtonSystemItemStop,
    camera:       UIBarButtonSystemItemCamera,
    trash:        UIBarButtonSystemItemTrash,
    play:         UIBarButtonSystemItemPlay,
    pause:        UIBarButtonSystemItemPause,
    rewind:       UIBarButtonSystemItemRewind,
    fast_forward: UIBarButtonSystemItemFastForward,
    undo:         UIBarButtonSystemItemUndo,
    redo:         UIBarButtonSystemItemRedo,
    page_curl:    UIBarButtonSystemItemPageCurl
  }[symbol] ||    UIBarButtonSystemItemDone

  item = UIBarButtonItem.alloc.
    initWithBarButtonSystemItem(name,
                                target:self,
                                action:action_name)
  item
end

#textfield(frame, placeholder = '', text = '', is_secure = false) ⇒ Object



407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/cha_work/basic.rb', line 407

def textfield(frame, placeholder='', text='', is_secure=false)
  frame = get_frame(frame)
  field                 = UITextField.alloc.initWithFrame(frame)
  field.placeholder     = placeholder.to_s
  field.secureTextEntry = is_secure
  field.borderStyle     = UITextBorderStyleNone
  # UITextBorderStyleRoundedRect
  field.returnKeyType   = UIReturnKeyNext
  field.delegate        = self
  field.text            = text.to_s
  field
end

#textview(args = {}) ⇒ Object



420
421
422
423
424
425
426
427
# File 'lib/cha_work/basic.rb', line 420

def textview(args={})
  frame = get_frame(args[:frame])
  tv = UITextView.alloc.initWithFrame(frame)
  tv.font = UIFont.systemFontOfSize(args[:font_size]) if args[:font_size]
  tv.layer.cornerRadius = args[:radius] if args[:radius]
  tv.delegate = self
  tv
end

#update_image(image_view, url, placeholder = 'photo') ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/cha_work/basic.rb', line 298

def update_image(image_view, url, placeholder='photo')
  return if url.nil? || url == ''

  if url.class == UIImage
    image_view.image = url
  elsif url.downcase.include? 'http'
    image_view.setImageWithURL(url.nsurl, placehoderImage:placeholder.uiimage)
  elsif url.class == String
    image_view.image = url.uiimage
  end
  image_view
end