Показаны сообщения с ярлыком Cocoa. Показать все сообщения
Показаны сообщения с ярлыком Cocoa. Показать все сообщения
Как работает метод convertRectToScreen: класса NSWindow
В окне три представления (NSView). Синее вложено в зеленое, а зеленое в красное. Красное представление находится прямо в окне.
Из чего состоит Cocoa-приложение работающее с Core Data
Базовый шаблон Cocoa Application проекта с поддержкой Core Data состоит из следующих файлов:
- AppDelegate.h
- AppDelegate.m
- ViewController.h
- ViewController.m
- Assets.xcassets
- Main.storyboard
- Info.plist
- Core_Data_Template.xcdatamodeld
- main.m
Рассмотрим все файлы и код в них чтобы понять какую роль они играют в проекте.
Кривые Безье в Cocoa на примере создания простой прямоугольной выноски
Рассмотрим как с помощью класса NSBezierPath можно нарисовать простую прямоугольную выноску.
NSBezierPath *thePath = [NSBezierPath bezierPath]; [thePath moveToPoint:NSMakePoint(NSMidX(aDirtyRect), NSMaxY(aDirtyRect))]; NSUInteger theArrWidth = 32, theArrHeight = 24; [thePath lineToPoint:NSMakePoint(NSMidX(aDirtyRect) + theArrWidth / 2, NSMaxY(aDirtyRect) - theArrHeight)]; [thePath lineToPoint:NSMakePoint(NSMaxX(aDirtyRect), NSMaxY(aDirtyRect) - theArrHeight)]; [thePath lineToPoint:NSMakePoint(NSMaxX(aDirtyRect), NSMinY(aDirtyRect))]; [thePath lineToPoint:NSMakePoint(NSMinX(aDirtyRect), NSMinY(aDirtyRect))]; [thePath lineToPoint:NSMakePoint(NSMinX(aDirtyRect), NSMaxY(aDirtyRect) - theArrHeight)]; [thePath lineToPoint:NSMakePoint(NSMidX(aDirtyRect) - theArrWidth / 2, NSMaxY(aDirtyRect) - theArrHeight)]; [thePath closePath]; [[NSColor colorWithDeviceWhite:1.0 alpha:1.0] setFill]; [thePath fill]; [[NSColor blueColor] setStroke]; [thePath stroke];
Крыша у выноски получилась более четкая, чем остальные краевые линии собственно потому что мы краевые линии рисовали на границе вьюхи. Тут не помешало бы сделать отступ с помощью NSInsetRect.
Если дальше развивать код, то с помощью функции curveToPoint:controlPoint1:controlPoint2: можно сделать закругленные углы, сделав тем самым скругленную прямоугольную выноску.
Если дальше развивать код, то с помощью функции curveToPoint:controlPoint1:controlPoint2: можно сделать закругленные углы, сделав тем самым скругленную прямоугольную выноску.
P.S. Кстати еще можно автоматически парсить SVG path и рисовать его на вью.
Как работает функция NSInsetRect?
Функция NSInsetRect смещает стороны прямоугольника на заданную величину.
Например, следующий код:
выдаст:
Например, следующий код:
[[NSColor redColor] setFill];
NSRectFill(aDirtyRect);
float theLineThickness = 50;
NSRect theContentRect = NSInsetRect([self bounds], theLineThickness, theLineThickness);
[[NSColor greenColor] setFill];
NSRectFill(theContentRect);
выдаст:
Изначально мы залили весь вью красным цветом. Потом с помощью функции NSInsetRect сместили стороны и по горизонтали и по вертикали на 50 единиц. И залили получившийся прямоугольник зеленым цветом. Ширина образовавшейся красной полоски составляет 50 px.
исходники
исходники
Что означает canBecomeKeyWindow?
Если метод canBecomeKeyWindow подкласса NSWindow возвращает YES, то фокус ввода переходит в показанное окно:
Разбираемся с NSDate
UTC — это всемирное координированное время, стандарт времени, принятый на Земле. От UTC отсчитываются часовые пояса. UTC заменил устаревшее время по Гринвичу (GMT). UTC расшифровывается как Coordinated Universal Time (по-английски).
Что такое NSResponder
NSResponder is one of the fundamental classes in Cocoa. Any class that can respond to events like key presses or menu commands should be a subclass of NSResponder. Each responder keeps track of it's "next responder", and each window keeps track of the object that's currently the "first responder". When an event happens in a window, a message is sent to the first responder. If that object handles the message, great. If not, it passes it along to its next responder. This is known as the "responder chain."
Normally, you don't mess much with the responder chain in Cocoa. The first responder is mostly determined by user actions, such as clicking on a control.
Как в Cocoa получить путь к папке с документами пользователя
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [NSString stringWithFormat:@"%@/", paths.firstObject];
Дайджест по программировании №19
- Showing and hiding an NSWindow programatically
- Yet Another Learn Cocoa With Me Blog: Custom cells in NSTableView (Part 1 - The NSCell version)
- iphone - How to detect the end of loading of UITableView - Stack Overflow
- WebKit: Forcing included files not to be cached
- NSLog the method name with objective-C in iPhone - Stack Overflow
- NSTableView | MyVeryLittleTricks
- Quickies for NSView
- shpakovski/Popup
- How do you clear the WebView cache in Cocoa? - lfter.com
- LEARN TO LOVE AUTO LAYOUT… PROGRAMMATICALLY
- iphone - Auto Layout (Constraints) Center 2 side by side views in a parent view - Stack Overflow
- xcode - NSTextField Vertical alignment - Stack Overflow
- osx - Forcing a Cocoa text field to end editing - Stack Overflow
- objective c - NSView Subclass drawRect gets called in an infinite Loop - Stack Overflow
- nxtbgthng/OAuth2Client
- Многопоточность в iOS. Введение в GCD
- NSTableView,NSTextFieldCell,NSCell,ImageAndTextCell tutorial
- NSTableView,NSTextFieldCell,NSImage,NSCell,ATImageAndTextCell tutorial
- Cocoa Dev Central: Cocoa Graphics with Quartz
- Migrate old project to ARC - Simon Shi
- Now that Xcode 5 supports doxygen annotation, it's time for you to start using it! | iOS Journeys
- Inline Documentation Comments for Objective-C Protocols and their Methods & Properties - Stack Overflow
- Documentation - NSHipster
- objective c - What are documentation comments in Xcode? - Stack Overflow
- objective c - How to include Doxygen method description in Xcode's autocomplete popup? - Stack Overflow
Иконки для Retina дисплея
В 2010 году вместе с iPhone 4 компания Apple запустила на рынок новую технологию — экраны ультравысокой четкости Retina Display. Сегодня ее можно увидеть также в планшетах и ноутбуках компании.
- Retina — Википедия
- Retina Iconset Trouble | Cocoanetics
- Unleash Your Inner App Developer Part 31: Managing Images with Xcode 5 Asset Catalogs | iPhoneLife.com
- Xcode Assets (*.xcassets) - Intertech Blog
- jduerr/Xcode-Cocoa-Retina-App-Icon-creator
- ios - Xcode 6 - xcassets for universal image support - Stack Overflow
Дайджест по саморазвитию в программировании №18
Visual Format Language
Learn to love Auto Layout… programmatically - Think & Build
Ambiguous Layout | Introducing iOS Auto Layout | InformIT
Drawing in Cocoa, Swift, Objective C using NSBezierPath
Making NSImages Resizable – Bureau de Cacao - rheard.com
objective c - Presenting modal dialogs from XIB in Cocoa: best/shortest pattern? - Code Review Stack Exchange
Interface Inspector
Python by Alan Richmond | ZEEF
Learn to love Auto Layout… programmatically - Think & Build
Ambiguous Layout | Introducing iOS Auto Layout | InformIT
Drawing in Cocoa, Swift, Objective C using NSBezierPath
Making NSImages Resizable – Bureau de Cacao - rheard.com
objective c - Presenting modal dialogs from XIB in Cocoa: best/shortest pattern? - Code Review Stack Exchange
Interface Inspector
Python by Alan Richmond | ZEEF
Circular Views
You can do the same sort of thing with
NSView instances: NSWindow *win = [self window];
NSView *a = [[NSView alloc] initWithFrame: NSMakeRect(0, 0, 1, 1)];
[a addSubview: a];
[[win contentView] addSubview: a];
(lldb) bt
* thread #1: tid = 0x458bf, 0x00007fff8c972528 AppKit`NSViewGetVisibleRect + 130, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=2, address=0x7fff5f3ffff8)
frame #0: 0x00007fff8c972528 AppKit`NSViewGetVisibleRect + 130
frame #1: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #2: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #3: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #4: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #5: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #6: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #7: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #8: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #9: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #10: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #11: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #12: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #13: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #14: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #15: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #16: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #17: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #18: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #19: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
frame #20: 0x00007fff8c9725c6 AppKit`NSViewGetVisibleRect + 288
источник
Какая разница между frame и bounds
bounds - это прямоугольник, заданный координатами (x,y) и размером (width,height) относительно собственной координатной системы (0,0).
frame - это прямоугольник, заданный координатами (x,y) и размером (width,height) относительно своего контейнера (superview).
--
iphone - Cocoa: What's the difference between the frame and the bounds? - Stack Overflow
frame - это прямоугольник, заданный координатами (x,y) и размером (width,height) относительно своего контейнера (superview).
--
iphone - Cocoa: What's the difference between the frame and the bounds? - Stack Overflow
Дайджест по саморазвитию в программировании №13
How to monitor file access for an OS X application?
OSX VM with 2D and 3D acceleration?
13.04 installed on Parallels on OSX. Very slow graphics performance
Xcode and Asynchronous Unit Testing
Asynchronous Unit Testing in Xcode 6
XCTestCase / XCTestExpectation / measureBlock()
How Do I Declare A Block in Objective-C?
Многопоточность в iOS. Введение в GCD, часть 4, семафоры.
OSX VM with 2D and 3D acceleration?
13.04 installed on Parallels on OSX. Very slow graphics performance
Asynchronous Unit Testing in Xcode 6
XCTestCase / XCTestExpectation / measureBlock()
How Do I Declare A Block in Objective-C?
Многопоточность в iOS. Введение в GCD, часть 4, семафоры.
Теги:
дайджесты,
многопоточность,
тестирование,
Cocoa,
GCD,
IDEF0,
links,
NSURLConnection,
Objective-C,
Xcode
Дайджест по саморазвитию в программировании №12
Agile Modeling (AM) Home Page: Effective Practices for Modeling and Documentation
Class Diagram Relationships UML | Examples Relationships Class Diagram
Паттерн Mapper - Распределитель
Message Factory and Message Interface Design Pattern
Модульный дизайн или «что такое DIP, SRP, IoC, DI и т.п.»
Stack Overflow:
iphone - How to make an progress bar for an NSURLConnection when downloading a file?
iphone - Implementing NSURLConnectionDataDelegate Protocol
Class Diagram Relationships UML | Examples Relationships Class Diagram
Паттерн Mapper - Распределитель
Message Factory and Message Interface Design Pattern
Модульный дизайн или «что такое DIP, SRP, IoC, DI и т.п.»
Stack Overflow:
iphone - How to make an progress bar for an NSURLConnection when downloading a file?
iphone - Implementing NSURLConnectionDataDelegate Protocol
Настройка типа документа в document-based Cocoa приложении
Для начала нужно выбрать нужный target в проекте, далее перейти на вкладку Info.
Если смотреть UTI файла с помощью утилиты mdls, то соответствие будет таким:
$ mdls exampleFile.exampleExtensionkMDItemContentType = "Identifier" kMDItemKind = "Name"
Примеры:
kMDItemContentType = "public.plain-text" kMDItemKind = "Документ простого текста" kMDItemContentType = "com.apple.xcode.model.data-version" kMDItemKind = "Versioned Core Data Model"
По умолчанию в методы:
- - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
- - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
в параметре typeName передается значение Name. Но если указан Identifier, то будет передаваться значение поля Identifier.
В поле Class указывается подкласс NSDocument.
В поле Extensions указывается расширение документа с которым работает приложение.
--
В поле Class указывается подкласс NSDocument.
В поле Extensions указывается расширение документа с которым работает приложение.
--
- Exported and Imported UTIs - Xcode Tools Sensei
- Technical Q&A QA1587: How do I get my application to show up in the "Open in..." menu on iOS for a specific document type?
- iOS Tips and Tricks: Associate a File Type with your App
- What are "Imported UTIs" in Xcode 4?
- Creating NSDocument using Folder Bundles and UTI Identifiers
- Fun with UTI | Cocoanetics
Подписаться на:
Сообщения (Atom)







