Domanda

I'm writing my application using Rubymotion rather than Objective-C/Xcode.

I find that a lot of Objective-C is written a lot more like procedural code than object oriented and I'm trying to keep my code neater and simpler than I see in most examples.

In saying that, is there any reason why I can't set the CurrentContext of a custom view as a method or property within my class? That is:

def drawRect(rect)
  context = UIGraphicsGetCurrentContext()
  redColor = UIColor.colorWithRed(1.0, green: 0.0, blue: 0.0, alpha:1.0)
  CGContextSetFillColorWithColor(context, redColor.CGColor)
  CGContextFillRect(context, self.bounds)

  # more drawing here ... 
end

Would become:

def drawRect(rect)
  setBackgroundRed
  # call more private methods to draw other stuff here
end

private

def context
  @context ||= UIGraphicsGetCurrentContext()
end

def setBackgroundRed
  CGContextSetFillColorWithColor(context, redColor)
  CGContextFillRect(context, bounds)
end

def redColor
  UIColor.colorWithRed(1.0, green: 0.0, blue: 0.0, alpha:1.0).CGColor
end

Thanks!

È stato utile?

Soluzione

It is inadvisable to store the context pointer across calls to drawRect. Each call to drawRect should make its own call to UIGraphicsGetCurrentContext() to get the context pointer. From there, pass it where it needs to go. You could do the following:

def drawRect(rect)
  context = UIGraphicsGetCurrentContext()
  setBackgroundRed(context)
  # call more private methods to draw other stuff here
end

private

def setBackgroundRed(context)
  CGContextSetFillColorWithColor(context, redColor)
  CGContextFillRect(context, bounds)
end

def redColor
  UIColor.colorWithRed(1.0, green: 0.0, blue: 0.0, alpha:1.0).CGColor
end

Altri suggerimenti

For simple scenarios like this you can just use the higher level API's, which are more OO in use. To fill a rect you don't need to drop down CoreGraphics as you can just use UIColor and UIBezierPath

UIColor.colorWithRed(1.0, green: 0.0, blue: 0.0, alpha:1.0).setFill

UIBezierPath.bezierPathWithRect(rect).fill
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top