Saving text labels on top of images - xcode

I'm building an app which takes Strings from the user and saves them using NSUserDefaults. Then I recover them and paste them on top of an image (a form or questionnaire) I'm currently saving the image with .write to file but when I check the image I've saved, I discovered that it doesn't save the full image and as a consequence the positions for the fields aren't right. I need to be able to send this image and later on print on a sheet of A4 paper.
The simulator :
http://postimg.org/image/5szujdgw3/
The saved image:
http://postimg.org/image/uq6mea6vb/
Why isn't it saving the full image?
Here's my code :
import UIKit
class StartMorgagesSave: UIViewController {
let rectangle = UIBezierPath(rect: CGRectMake(80, 166, 80, 05)) //x , y , width , height 240, 165
let shapeLayer = CAShapeLayer()
//let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
shapeLayer.path = rectangle.CGPath
shapeLayer.strokeColor = UIColor.blueColor().CGColor
shapeLayer.fillColor = UIColor.whiteColor().CGColor
view.layer.addSublayer(shapeLayer)
view.pdfData.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("test53.pdf"), atomically: true) // what it is saved as
view.pdfData.writeToFile("fdfdlo", atomically: false)
print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.path!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UIView {
var pdfData: NSData {
let result = NSMutableData()
UIGraphicsBeginPDFContextToData(result, frame, nil)
guard let context = UIGraphicsGetCurrentContext() else { return result }
UIGraphicsBeginPDFPage()
layer.renderInContext(context)
UIGraphicsEndPDFContext()
return result
}
}
Niall

Related

How can I implement a tab bar like the ones in Xcode?

There does not seem to be any standard AppKit control for creating a tab bar similar to the ones found in Xcode.
Any idea on whether this is possible or would I need to use a custom control of some sort, and if so any suggestions on whether any are available.
OK I figured it out by subclassing NSSegementedControl to get the desired behaviours.
import Cocoa
class OSSegmentedCell: NSSegmentedCell {
override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
// Do not call super to prevent the border from being draw
//super.draw(withFrame: cellFrame, in: controlView)
// Call this to ensure the overridden drawSegment() method gets called for each segment
super.drawInterior(withFrame: cellFrame, in: controlView)
}
override func drawSegment(_ segment: Int, inFrame frame: NSRect, with controlView: NSView) {
// Resize the view to leave a small gap
let d:CGFloat = 0.0
let width = frame.height - 2.0*d
let dx = (frame.width - width) / 2.0
let newRect = NSRect(x: frame.minX+dx, y: frame.minY, width: width, height: width)
if let image = self.image(forSegment: segment) {
if self.selectedSegment == segment {
let tintedImage = image.tintedImageWithColor(color: NSColor.blue)
tintedImage.draw(in: newRect)
} else {
image.draw(in: newRect)
}
}
}
}
extension NSImage {
func tintedImageWithColor(color:NSColor) -> NSImage {
let size = self.size
let imageBounds = NSMakeRect(0, 0, size.width, size.height)
let copiedImage = self.copy() as! NSImage
copiedImage.lockFocus()
color.set()
__NSRectFillUsingOperation(imageBounds, NSCompositingOperation.sourceIn)
copiedImage.unlockFocus()
return copiedImage
}
}

Xcode Swift image zoom gesture

Hope someone can help me. Im trying to make a zoom gesture, so when the image are presented the user can zoom the image with fingers.
My code to present the image are:
// MARK: Show image full screen
func imageTapped(img: AnyObject) {
self.navigationController?.navigationBarHidden = true
let imageView = productImage as UIImageView
let newImageView = UIImageView(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = .blackColor()
newImageView.contentMode = .ScaleToFill
newImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: "dismissFullscreenImage:")
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
func dismissFullscreenImage(sender: UITapGestureRecognizer) {
sender.view?.removeFromSuperview()
self.navigationController?.navigationBarHidden = false
}
Use UIScrollView and add UIImgeView in scroll view
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate
{
var scrollV : UIScrollView!
var imageView : UIImageView!
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
scrollV=UIScrollView()
scrollV.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
scrollV.minimumZoomScale=1
scrollV.maximumZoomScale=3
scrollV.bounces=false
scrollV.delegate=self;
self.view.addSubview(scrollV)
imageView=UIImageView()
imageView.image = UIImage(imageLiteral: "neymar.jpg")
imageView.frame = CGRectMake(0, 0, scrollV.frame.width, scrollV.frame.height)
imageView.backgroundColor = .blackColor()
imageView.contentMode = .ScaleToFill
scrollV.addSubview(imageView)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
{
return imageView
}
}
Take gesture programmatically and make its method and write down this code in the method.
pinchRecognizerOnView() is my method name. Take one view or image view inside view controller and add this new view in that.Now apply gesture method on this new view.
func pinchRecognizerOnView(sender: UIPinchGestureRecognizer!) {
sender.view?.transform = CGAffineTransformScale((sender.view?.transform)!, sender.scale, sender.scale)
sender.scale = 1
// its for zoom in out screen
}

After running an animation in xcode I need the UIImage to change to a different static image

So the code under the didRecieveMemoryWarning doesn't seem to be called after the animation is completed. What I want the animation to do is when the UIbutton is pressed it shows a series of UIImages being shuffled through and then after 6 repeat counts it stops on a random static image based on:
#IBAction func playRoundTapped(sender: UIButton) {
let firstRandomNumber = arc4random_uniform(2) + 1
let firstCardString:String = String(format: "side%i", firstRandomNumber)
self.firstDiceImageView.image = UIImage(named: firstCardString)
}
However for some reason everytime the animation completes it goes back to the "card_default" static image instead of the "side%i" randomized image.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Setting UIImages to Default
self.firstDiceImageView.image = UIImage(named: "card_default")
self.secondDiceImageView.image = UIImage(named: "card_default")
self.thirdDiceImageView.image = UIImage(named: "card_default")
self.forthDiceImageView.image = UIImage(named: "card_default")
//Animation For Loop
for i in 1...4
{
myImages.append(UIImage(named: "\(i)")!)
}
firstDiceImageView.animationImages = myImages
firstDiceImageView.animationRepeatCount = 6
firstDiceImageView.stopAnimating()
secondDiceImageView.animationImages = myImages
secondDiceImageView.animationRepeatCount = 6
thirdDiceImageView.animationImages = myImages
thirdDiceImageView.animationRepeatCount = 6
forthDiceImageView.animationImages = myImages
forthDiceImageView.animationRepeatCount = 6
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playRoundTapped(sender: UIButton) {
let firstRandomNumber = arc4random_uniform(2) + 1
let firstCardString:String = String(format: "side%i", firstRandomNumber)
self.firstDiceImageView.image = UIImage(named: firstCardString)
}

UITextKit and exclusionPaths: undependable indent when editing

I have a problem with UITextKit using exclusionPaths: when I place an image inside a TextView, that I’m editing, first everything looks fine:
But when the „Done“-Button is tapped, it will look like this, the ident is wrong:
This is the class to store the informations for the image
class ImageClass {
var image: UIImage!
var imageView: UIImageView
var imageName: String!
var active:Bool
var exclusivePath: UIBezierPath!
init(image: UIImage!, imageName: String!) {
self.image = image
imageView = UIImageView(image: image!)
self.imageName = imageName
self.active = false
self.exclusivePath = nil
}
}
The user chooses the image in a UICollectionView that fires a delegate, when the image was selected. (imageViewObjects is an array, where I can put objects of ImageClass, so I can use mutiple images)
// MARK: - SelectImageDelegate
func selectedImage(name:String) {
let image = UIImage(named: name)
let imageViewObject = ImageClass(image: image, imageName: name)
self.imageViewObjects.append(imageViewObject)
imageViewObject.imageView.frame = CGRectMake(4, 7, width!, height!)
// define the exlusionPaths
let bezierPath = self.exclusionPathForImageView(imageViewObject.imageView)
imageViewObject.exclusivePath = bezierPath
self.updateExclusionPaths()
self.textView.addSubview(imageViewObject.imageView)
}
// set UIBezierPath for the UIImageView
func exclusionPathForImageView(imageView: UIImageView) -> UIBezierPath {
let bezierPath = UIBezierPath(rect:
CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y,
imageView.frame.width, imageView.frame.height))
return bezierPath
}
func updateExclusionPaths() {
textView.textContainer.exclusionPaths = []
for imageViewObject in self.imageViewObjects {
textView.textContainer.exclusionPaths.append(imageViewObject.exclusivePath)
}
}
The context of bezierPath is ok.
When „Done“ is tapped, I stop the editing
let doneBarButton = UIBarButtonItem(title: "Done", style: .Done, target: view, action: Selector("endEditing:"))
In textViewDidEndEditing() now I do nothing.
I also tried it with a UIButton for the image. Similar result.
Any tip for a solution? plz help me!!!!
found a workaround:
func textViewShouldEndEditing(textView: UITextView) -> Bool {
textView.editable = false
}
and I had to add to set textView.editable = true, i.e. in viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "resetEditable")
tapGesture.numberOfTapsRequired = 1
self.textView.addGestureRecognizer(tapGesture)
func resetEditable() {
textView.editable = true
textView.becomeFirstResponder()
}

NSPopUpButton arrow color

Is there a way to customize the color of a NSPopUpButton arrow? I've looked around but I've not found an answer yet
I really dont think there is an "easy" way to do this. If you look at the API description, it even states that it doesnt respond to the setImage routine. I have done quite a bit of work sub-classing button objects, etc... and I think this is where you would have to go in order to do what you are asking.
Like too many of these controls, I did it by subclassing NSPopupButton(Cell) and then doing all my own drawing in drawRect...I cheated a little though, and used an image do the actual triangle rather than trying to do it via primitives.
- (void)drawRect:(NSRect)dirtyRect
{
//...Insert button draw code here...
//Admittedly the above statement includes more work than we probably want to do.
//Assumes triangleIcon is a cached NSImage...I also make assumptions about location
CGFloat iconSize = 6.0;
CGFloat iconYLoc = (dirtyRect.size.height - iconSize) / 2.0;
CGFloat iconXLoc = (dirtyRect.size.width - (iconSize + 8));
CGRect triRect = {iconXLoc, iconYLoc, iconSize, iconSize};
[triangleIcon drawInRect:triRect];
}
i did this and its worked for me.
(void)drawImageWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
NSPopUpButton *temp = (NSPopUpButton*)controlView;
NSString *strtile = temp.title;
AppDelegate *appdel = (AppDelegate*)[NSApplication sharedApplication].delegate;
NSFont *font = [NSFont systemFontOfSize:13.5];
NSSize size = NSMakeSize(40, 10);// string size
CGRect rect = controlView.frame;
rect = CGRectMake((size.width + temp.frame.size.width)/2, rect.origin.y, 8, 17);
[self drawImage:[NSImage imageNamed:#"icon_downArrow_white.png"] withFrame:rect inView:self.
}
I have changed arrow color by using "False Color" filter without using any image. So far it is the easiest way to change cocoa control to me.
class RLPopUpButton: NSPopUpButton {
init() {
super.init(frame: NSZeroRect, pullsDown: false)
addFilter()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addFilter()
}
func addFilter() {
let colorFilter = CIFilter(name: "CIFalseColor")!
colorFilter.setDefaults()
colorFilter.setValue(CIColor(cgColor: NSColor.black.cgColor), forKey: "inputColor0")
colorFilter.setValue(CIColor(cgColor: NSColor.white.cgColor), forKey: "inputColor1")
// colorFilter.setValue(CIColor(cgColor: NSColor.yellow.cgColor), forKey: "inputColor0")
// colorFilter.setValue(CIColor(cgColor: NSColor.property.cgColor), forKey: "inputColor1")
self.contentFilters = [colorFilter]
}
}
Swift 5
In interface builder, remove default arrow setting.
Then, apply this subclass for cell, which will add an NSImageView to the right side of the NSPopUpButton.
This way you have complete control over what you set as your custom button and how you position it.
import Cocoa
#IBDesignable class NSPopUpButtonCellBase: NSPopUpButtonCell {
let textColor = NSColor(named: "white")!
let leftPadding: CGFloat = 16
let rightPadding: CGFloat = 30
override func awakeFromNib() {
super.awakeFromNib()
let imageView = NSImageView()
imageView.image = NSImage(named: "ic_chevron_down")!
controlView!.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: CGFloat(20)).isActive = true
imageView.heightAnchor.constraint(equalToConstant: CGFloat(20)).isActive = true
imageView.trailingAnchor.constraint(equalTo: controlView!.trailingAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: controlView!.centerYAnchor).isActive = true
}
// overriding this removes the white container
override func drawBezel(withFrame frame: NSRect, in controlView: NSView) {
}
// overriding this allows us to modify paddings to text
override func titleRect(forBounds cellFrame: NSRect) -> NSRect {
// this gets rect, which has title's height, not the whole control's height
// also, it's origin.y is such that it centers title
let processedTitleFrame = super.titleRect(forBounds: cellFrame)
let paddedFrame = NSRect(
x: cellFrame.origin.x + leftPadding,
y: processedTitleFrame.origin.y,
width: cellFrame.size.width - leftPadding - rightPadding,
height: processedTitleFrame.size.height
)
return paddedFrame
}
// overriding this allows us to style text
override func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect {
let attributedTitle = NSMutableAttributedString.init(attributedString: title)
let range = NSMakeRange(0, attributedTitle.length)
attributedTitle.addAttributes([NSAttributedString.Key.foregroundColor : textColor], range: range)
return super.drawTitle(attributedTitle, withFrame: frame, in: controlView)
}
}

Resources