Wednesday 7 September 2011

iOSDev UK: Building Custom Controls with UIView

Rory Prior, ThinkMac Software, @roryprior

  • generally subclass UIView directly
    • can subclass other controls, but things might not happen how you expect since lots of things happen in the background
    • and you may need to use private APIs…
  • override methods:
    • initWithFrame for programmatic creation
    • initWithCoder for IB-created views
    • drawRect for actual drawing
  • UIKit uses top left as origin
    • but CoreGraphics uses bottom left…
  • adding UIImageView is easy
    • but quite heavyweight
    • instead can draw a UIImage directly
  • similarly, can use UILabel or draw string directly
    • NSString drawAtPoint:withFont:
    • NSString drawInRect:withFont:
    • NSString sizeWithFont:
  • drawing shapes:
    • CoreGraphics (nasty low-level C stuff :-) )
    • UIBezierPath (introduced in iOS 3.2)
  • complicated graphics often still done better by using bitmaps — UIBezierPath can be processor-intensive for lots of lines
  • UIColor can fill in patterns as well as flat colour

user interaction

  • override UIResponder methods to detect touches
  • you’ll need UIGestureRecognizers to detect swipes, pinches, etc
  • but use sub-views of UIButton etc to make thins much easier
  • see slides for nice example of adding UIResponder and UIGestureRecognizer
  • use the delegate pattern to send feedback from your view to the rest of your app

No comments: