Thursday, February 14, 2013

http://www.say7.info/cook/recipe/259-Borsch.html

http://www.say7.info/cook/recipe/259-Borsch.html

Борщ

Борщ

Ингредиенты

Борщ. Ингредиенты
  • 1 кг говядины (мякоть или на косточке)
  • 500 г картофеля
  • 300 г свежей капусты
  • 400 г свеклы
  • 200 г моркови
  • 200 г лука
  • 3 ст.л. томатной пасты
  • 1 ч.л. уксуса 6%
  • 2-3 зубчика чеснока
  • 2-3 лавровых листа
  • соль
  • перец
  • растительное масло
  • зелень по вкусу

Приготовление


Количество ингредиентов указано на четырехлитровую кастрюлю.


Фото 1Мясо залить водой, варить 1.5 часа.

Фото 2Затем мясо нарезать небольшими кусочками.

Фото 3Добавить в бульон.

Фото 4Лук мелко покрошить.

Фото 5Морковь натереть на средней терке.

Фото 6Капусту нашинковать тонкой соломкой.

Фото 7Свеклу нарезать тонкой соломкой.

Фото 8Свеклу обжарить на растительном масле.

Фото 9Добавить уксус и томатную пасту (если паста густая, добавить немного воды), тушить 5-7 минут.

Фото 10На растительном масле обжарить лук.

Фото 11Добавить морковь, обжарить.

Фото 12Картофель нарезать кубиками или брусочками.

Фото 13В кипящий бульон добавить картофель, посолить.

Фото 14Когда бульон закипит, добавить капусту. Варить на небольшом огне 5 минут.

Фото 15Добавить свеклу, варить еще около 10 минут.

Фото 16Добавить лук и морковь.

Фото 17Следом добавить лавровый лист. Если необходимо, посолить, поперчить.

Фото 18Добавить чеснок, выдавленный через чеснокодавку.
Убрать с огня, дать настояться 15-20 минут. 
Готовый борщ разлить по тарелкам, добавить сметану и посыпать зеленью.

КнигаВышла книга с рецептами сайта.
Все подробности здесь:
http://forum.say7.info/topic44751.html
Спрашивайте во всех книжных магазинах вашего города.

КнигаВышла вторая книга с рецептами сайта.
Все подробности здесь:
http://forum.say7.info/topic58168.html
Спрашивайте во всех книжных магазинах вашего города.

Приятного аппетита!


Рецепт от Анастасии Скрипкиной

Рецепт добавлен 19.02.2007 
Отправить другу 
Версия для печати

Tuesday, February 12, 2013

Портал по открытому ПО, Linux, Unix и BSD системам http://www.opennet.ru

Портал по открытому ПО, Linux, Unix и BSD системам

Обзор основных форматов субтитров http://torrents-nn.cn/showthread.php?t=345016

 
Обзор основных форматов субтитров

SubRipper (*.srt)


Файлы имеет расширение srt. Сам формат отличается простотой и наглядностью, синхронизация с видео на основе времени с точностью до микросекунд. Весьма распространенный формат. Srt файлы очень удобно редактировать - перевод лучше делать именно в srt файлах. Главный недостаток - формат не позволяет изменять параметры шрифта (размер, стиль, цвет) и положение субтитров на экране. Шапки - нет. Конец файла отмечается удвоенным переводом строки.


Код:
1  00:02:58,000 --> 00:03:00,880  [Токийская школа истребителей нечисти]  Перевод: over  Редакция: Danphil & Tany Sword  DOTeam - www.viManga.ru  2  00:03:01,090 --> 00:03:04,890  [Глава "Темный закон" Ночь Первая]  3  00:03:05,080 --> 00:03:06,910  [Час демона]
N
ЧЧ:ММ:СС:МКС --> чч:мм:сс:мкс
Первая строка фразы
Вторая строка фразы
где
N - номер фразы
ЧЧ:ММ:СС:МКС - время начала показа фазы в часах минутах, секундах и миллисекундах (мкс)
чч:мм:сс:мкс - время начала показа фазы в часах минутах, секундах и миллисекундах (мкс)
между временем и стрелкой пробел. Фразы отделяются друг от друга пустой строкой.



SubStation Altha (.ass)


Формат *.ssa это рабочий файл субтитров программы SubStation Altha . Это программа для подготовки и таймирования субтитров. Среди непрофессионалов это самая популярная и богатая возможностями программа для титрования. Также богат и сам формат субтитров. Здесь полностью поддерживается работа со всеми параметрами шрифта (цвет, размер, гарнитура и т.д.). размещение текста в любом месте экрана, комментарии.Множество полей определяет параметры каждой фразы, например специальное поле для определения произносящего данную фразу. Кроме текста можно вставлять картинки , звуки и даже маленькие видео фрагменты. Этот формат является фактически стандартом де-факто в среде фэнсаберов. Все это делает формат SSA преобладающим в среде анимешников.


Код:
[Script Info]  ; Script generated by Aegisub v2.00 PRE-RELEASE (SVN r1515, ArchMageZeratuL)  ; http://www.aegisub.net  ScriptType: v4.00+  PlayResX: 704  PlayResY: 400  WrapStyle: 0  Collisions: Normal  Video Aspect Ratio: 0  Video Zoom: 6  Video Position: 0  Last Style Storage: ghost hound  [V4+ Styles]  Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour,  OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX,  ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment,  MarginL, MarginR, MarginV, Encoding  Style: Default,Arial,20,&H00FFFFFF,&H0000FFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,0  Style: Dialogue,Chantelli  Antiqua,28,&H00ECECEC,&H000000FF,&H003C4930,&H004A593B,-1,0,0,0,100,95,0,0,1,2,0.5,2,10,10,10,0  Style: Preview Style,Chantelli  Antiqua,28,&H00ECECEC,&H000000FF,&H32115C2C,&H000C4120,-1,0,0,0,100,100,0,0,1,2,0.5,2,10,10,10,0  Style: TL Notes,Chantelli  Antiqua,22,&H00ECECEC,&H000000FF,&H00363636,&H00000000,0,0,0,0,100,100,0,0,1,2,0.5,8,10,10,10,0  Style: comment,Arial,20,&H00747D7F,&H0000FFFF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,2,2,8,10,10,10,0  Style: comment2,Arial,20,&H00FFFFFF,&H0000FFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,8,10,10,10,0  Style:  ghost,BenguiatGothicCTT,32,&H00FFFFFF,&H0000FFFF,&H00414143,&H00414143,-1,0,0,0,100,100,0,0,1,2,2,2,10,10,10,0  Style: title,B52,72,&H00A4ACAD,&H0000FFFF,&H00000000,&H00FFFFFF,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,0  [Events]  Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text  Dialogue: 0,0:00:36.00,0:00:36.50,comment,,0000,0000,0000,,{\frz8\fs25\pos(441,279)}Двое детей похищены в Суйтене  Dialogue:  0,0:00:36.50,0:00:37.20,comment,,0000,0000,0000,,{\frz74\fs25\pos(370,198)}Несчаcтный  случай, \Nпроизошедший с преступником
Скрипт состоит из заголовка, описания стилей и тела=
В заголовке [Script Info] есть стандартная часть , которая сообщает что это за файл и версию скрипта, а также отсылает к сайту SubSttaion Altha.
Далее идут несколько полей обозначающих автора перевода, источник откуда сделан перевод , точку синхронизации (при выводе на аналоговый носитель синхронизация производится вручную), разрешение с которым работал редактор при расположении элементов по экрану и некоторые другие.
В разделе стилей [V4 Styles] идет детально описание всех используемых в скрипте стилей. указывается размер, гарнитура, стиль и цвет шрифта, положение (в виде отступов справа , слева , сверху и снизу), а также кодировку.
Далее идет раздел [Events] в котором располагается последовательность текстовых фраз, комментариев, а также комманд на показ логотипа, проигрывания музыки или видеофрагмента.
Для каждой из фраз отдельно можно указать время начала и конца показа этой фразы, ее стиль , название (используется как поля для указание имени говорившего) и положения фразы на экране. Далее идет сам текст фразы, разделение на строки как в языке C с помощью комбинации "/n".




Програмы перевода и тайминга.
Первое выдираем тайминг с авишки программой AviSubDetector (здесь)
Программа, которая по вшитым в картинку субтитрам создаёт разметку времени для внешних субтитров.



1. Запускаем AviSubDetector.
2. Жмем Open AVI и выбираю файл, с которого хотим выдрать сабы. В закладке Project видим выбранный файл, возле которого стоит галочка.
3. Жмем Automatic Mode, затем Start (Full) - программа начала выдирать тайминг. Жмем на закладку Subtitles - видим, как определяются Frame и появляются непонятные для нас (но хорошо понятные разным плеерам) наборы символов.
4. Переходим на закладку Settings - в окошке просмотра смотрим начало мульта, поджидая, когда же закончится опенинг. Как только видим первый титр, жмем в верхнем углу Pause.
5. Начинаем самое интересное - английские титры. Жмем кнопку OCR (возле Automatic Mode). И снова Start (Full).
6. Учим распознавать символы: сначала прийдется потрудиться. Появляется большое окно, в котором показывается найденный символ.
Он или очень нам нужный - буквы (прописные, строчные, наклонные и т.д.), цифры, знаки препинания (здесь сложнее, т.к., скорее всего, появится много лишних точек, тире и т.д. Лично я из знаков препинания использую только , и ? Точки и ! использую уже в процессе перевода). В среднем, если с нуля, то я в серии мульта присваиваю где-то 70-110 символов.
7. Дальше можно или сидеть у экрана, ожидая появления незнакомых редких символов, или же жмем на закладку OCR, выбираем Main, и там уже жмем две кнопки REMOVE Unknown и All (программа будет пропускать все неопознанные символы). Жмем на закладку Subtitles - видим, как определяются Frame и появляются, о чудо, английские титры.
8. Да, не забываем сохранять выдранные титры: закладка Subtitles, кнопка Save (как сохранять файл объяснять не буду). Сохранять можно в любой момент, думаю, стоит это делать почаще.


Второе, на данный момент используют в основном:
"Aegisub" (здесь),
Одна из самых удобных программ для создания и обработки субтитров в форматах ass и ssa.
"ChronoSub" ("Medusa") (здесь)
Ещё одна титровалка «всё-в-одном», пришедшая на смену СабСтэйшну. Работает с форматом ASS, понимает ssa, xss, srt, sub, psb и простые txt.
Добытый тайминг открывается в любой из этих прог, там же открываем видео и соответственно набиваем там и перевод и сохраняем результат в желаемом формате.
Завершающий этап, просмотр своего творения ещё и раз на предмет кривых и неправильно переведённых фраз и обязательная прогонка "Вордом" на ошибки...



http://subs.com.ru/page.php?al=ssa_description
или даже полезней скачать и всегда держать под рукой:
http://subs.com.ru/datas/tmp/article..._specs_rus.zip

оригинал на английском (в формате .doc) скачать:
http://subs.com.ru/datas/tmp/article.../ass-specs.zip

Так-же, вот это вы возможно уже всё знаете, но всё-таки:
http://subs.com.ru/page.php?al=create_subs_with_aegisub

и полная документация к работе с программой на английском:
http://aegisub.cellosoft.com/docs/Main_Page

подраздел со спецификацией ASS (хорошо оформлен, с иллюстрациями):
http://aegisub.cellosoft.com/docs/ASS_Tags


Что делать если неподходит тайминг | подбивка тайминга по "Aegisub"

Тогда можно в том же Аегисабе двигать, он более дружелюбен к "ass и ssa"
Если весь саб отстаёт, запускаем видео - запоминаем время начальной фразы -> Редактировать> Сдвиг по времени> далее выбираем в меню "сдвиг на..." куда нужно "вперёд" или "назад" двинуть, в окошечке выше вводим нужное кол-во, в меню "Задействовать"ставим галочку "все строки" и "ок".
Так же и с отдельныи фрагментыми можно поступать, только в главно меню Аеги выделить их нажав "ctrl" и выделив нужное кол-во строк мышью.
И в меню "Задействовать" ставим галочку на "выбранные строки", а остальной порядок тот же самый что и выше...


Подбивка тайминга по Dsrt (Здесь)


Перед ретаймированием производится сортировка скрипта по времени, т.е. ретаймирование производится по времени, а не по положению фраз в скрипте. Ретаймирование может потребоваться в случае если тайм-код линейно отстает или опережает звуковое сопровождение. Для ретаймирования требуется как минимум две отмеченные фразы [Ctrl+F2], однако ретаймирование возможно по любому количеству точек (отмеченных фраз), в этом случае для каждых двух смежных точек будет использован собственный коэффициент сжатия/растяжения. Для каждой отмеченной фразы можно задать сдвиг (в мс.) в окне ретаймирования [F5] сдвиг определяет начальное и конечное время фразы после ретаймирования, т.е. если указать значение сдвига -1000, то после ретаймирования от начального и конечного времени отмеченной фразы будет вычтена секунда. Ретаймирование оказывает влияние и на продолжительность фраз: если интервал между отмеченными фразы будет сжат, то и продолжительность всех фраз будет сжата соответственно коэффициенту сжатия, рассчитанному на основе сдвигов смежных точек. Данная процедура исключает возможность появления новых коллизий в скрипте. Для отмеченных фраз действуют ограничения на пересечение интервалов ретаймирования между собой и на пересечение с участками скрипта не подверженными ретаймированию. Рассмотрим это на примере:
1
00:01:52,218 --> 00:01:53,000 Конечное время фразы - предел для сдвига след. за ней отмеченной
Pervert!
2
00:01:53,153 --> 00:01:54,554 Отрицательный сдвиг для данной фразы возможен только до -153мс.
I'm not a pervert!
3
00:01:54,554 --> 00:01:56,823
You were peeping at the girls at work!
4
00:01:56,823 --> 00:01:59,559
It just smelled good, that's why I was there.
5
00:01:59,559 --> 00:02:01,061 Сдвиг возможен до конечного времени предыдущей точки с учетом ее сдвига
Who'd want to look at a girl like you?
5-я фраза является отмеченной и последней в скрипте, поэтому для нее возможен любой (в разумных пределах) положительный сдвиг, отрицательный сдвиг возможен только до конечного времени предыдущей отмеченной фразы с учетом ее сдвига. Для 2-й фразы возможен положительный сдвиг до начала следующей отмеченной фразы с учетом ее сдвига. Если отмеченной является первая фраза в скрипте, то для нее левым пределом является нулевое время. Простейшее ретаймирование производится путем отметки первой и последней фразы и заданием для них сдвигов. В этом случае ретаймирование эквивалентно вызову функции "Скрипт->Сжать/растянуть весь скрипт" [Shift+F5].
Перед ретаймированием стоит убедиться, что оно действительно необходимо, возможно скрипт просто сдвинут в нескольких местах, в этом случае скрипт стоит попробовать исправить в окне "Видео".
В окне ретаймирования имеется кнопка "Синхронизация", с помощью данной кнопки можно синхронизировать скрипты в разных переводах. Например у нас имеется английский скрипт с правильным тайм-кодом и русский с отстающим или убегающим вперед тайм-кодом. В английском и русском скриптах отмечаем равное количество одинаковых фраз. Т.е. в русском и английском скриптах должно быть отмечено N фраз одинакового значения. (каждой английской отмеченной фразе ставим в соответствие ее перевод в русском скрипте). Переходим в русский скрипт, открываем окно ретаймирования и нажимаем кнопку "Синхронизировать" в открывшемся окне выбираем английский скрипт в качестве шаблона, после чего нажимаем кнопку "Ретаймировать". Если фразы были выбраны правильно, то получаем русский скрипт с правильным тайм-кодом.
В окне ретаймирования доступны еще 2 кнопки: "Сохранить" и "Загрузить". Кнопки служат для сохранения списка отмеченных фраз и сдвигов. С помощью кнопки "Сохранить" можно сохранить помеченные фразы и сдвиги для них в отдельный файл (*.dtc). Кнопка "Загрузить" загружает dtc-файл и адаптирует сохраненные фразы и сдвиги для них к текущему скрипту. Адаптация происходит в случае если скритп отличается от того для которого происходило сохранение отмеченных фраз. Основная область применения - это создание файлов небольшого размера (<100b) достаточных для генерации готовых субтитров для разных рипов из одного и того же комплекта субтитров. Технология изготовления dtc-файлов будет выглядеть следующим образом: открываем скрипт, расставляем отмеченные фразы в ключевых точках (рекомендую всегда отмечать первую и последнюю в числе прочих) устанавливаем сдвиги необходимые для приведения скрипта ко второму рипу, ретаймируем, проверяем синхронизацию аудио с субтитрами, делаем откат до момента ретаймирования (можно использовать резервную копию) и сохраняем dtc-файл.



Увеличение размера шрифта Aegisub:

Saturday, February 9, 2013

kissXML http://www.cyberforum.ru/objective-c/thread625924.html




kissXML example
NSData *xmlData;//откуда то данные в формате xml
DDXMLDocument *xmlDoc = [[DDXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if (error || !xmlLib) {
   [xmlDoc release];
   /*обработка ошибки*/
} 
NSArray *items = [xmlDoc nodesForXPath:@"//a" error:&error];
for (DDXMLElement *item in items) {
     Page *page = [[Page alloc] init];
     NSString *imageURL = [[item attributeForName:@"key1"] stringValue];
     if ([[item attributeForName:@"some_attr"] stringValue]) {
        [self proceedKaraokeDDXMLElement:item forPage:page];
     }
     /*Делаем чтото с page*/
}

Parse XML Files in Style http://makeshiftgames.com/2010/08/30/parse-xml-files-in-style/

http://makeshiftgames.com/2010/08/30/parse-xml-files-in-style/

Parse XML Files in Style

Posted by: jamesj3k In: Development

One would think that parsing and generating xml files using the iPhone SDK would be a simple task.  However, Apple decided to leave out the NSXML and related classes from the SDK.  So- out of the box, that leaves us with NSXMLParser.  No thanks.

My first question was: How can I deal with xml the way I'm used to- the way C#, ActionScript, and to a lesser extent JavaScript handle it.  The answer is the wonderful KissXML package.

Now we can do things like this:

  NSString * fileContents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error:nil];  DDXMLDocument * doc = [[DDXMLDocument alloc] initWithXMLString: fileContents options:0 error:nil];  DDXMLElement * root = [doc rootElement];  NSDictionary * mapAttribs = [root attributesAsDictionary];    mapSize.width = [[mapAttribs valueForKey:@"width"] intValue];  mapSize.height = [[mapAttribs valueForKey:@"height"] intValue];    DDXMLElement * tilemap = [[root elementsForName:@"tilemap"] objectAtIndex:0];  NSString * source = [[tilemap attributeForName:@"source"] stringValue];

Not as good as C#, but much better than NSXMLParser. Happy XMLing.


Sunday, February 3, 2013

Putting a Button in a Table http://osmorphis.blogspot.ru/2009/04/putting-button-in-table.html

http://osmorphis.blogspot.ru/2009/04/putting-button-in-table.html

April 9, 2009

Putting a Button in a Table

Sometime you may need to add a button to the contents of a UITableViewController. While you have the ability to put buttons in the navigation bar or in a toolbar at the bottom, it is sometimes best to simply put the button "inline" near your data. Sure, you could simply put a UIButton control right in a UITableCell object, but I have found the results of that not very attractive, especially in grouped tables. So what's the best way? I like to use the Apple applications as examples of good design. There are a couple Apple applications that put UIButtons in UITableViewControllers. Take a look at these examples. This one is from the mail settings, where there is a "Delete Account" button at the bottom of the table: 
And this one is when you are editing a contact, where there is another "Delete" button at the bottom: 
Although they are the same size of a single cell section, you can tell these are not normal rows. The giveaways are the rounded corners that don't quite match those of the neighboring rows. My guess is these are custom buttons, which stretch a background image to fit a frame that's the same size of a cell. But using UIButton controls is not the only way to get button behavior. You can simulate a button with just a basic grouped table cell; no UIButton at all. This is what I call cell-based buttons, for lack of a better term. I found a couple Apple applications that appear to use this technique. For example, here is the the settings from Safari: 
That section of three rows in the middle contain cells where each operates as a button. The phone settings also uses this, with the "Change Voicemail Password" cell in the middle. There are probably other ways to get button functionality into your tables, but these two seem to be the most common. This article will explain the advantages and disadvantages of each approach, and I'll provide some code snippets that shows how to do them. 

Cell-Based Buttons

Simulating a button in a cell has one big advantage: it's super easy to do. If you don't care about it looking fancy, or want to bunch up several "buttons" in one section, as the one above for editing a contact, then a cell-based button is a good option. For simple black on white text, all you have to do is set the cell.text property to your button text. Since the visual aspects of a table cell can be customized quite extensively, you really have lots of flexibility here. However, once you go beyond the standard UITableCell object, the complexity of your code increases. I believe that once you have gone beyond the basic black on white text, you might as well go with a real button. 

Implementing

How a cell-based button works is that your code simply traps the tableView:didSelectRowAtIndexPath: message. You associate the section and row with which "button" was hit and perform whatever action that button is supposed to do. For example, from the image above, you can associate that block of buttons with section #1, and row #0 is the "Clear History" button, row #1 is "Clear Cookies", etc. One thing to remember is that the action of touching a cell automatically highlights the cell. Before you do anything else, you should turn off that highlight. Here is some example code of how we might implement the above section of three buttons. There are two aspects here: setting up the buttons for display, and handling the actions when the buttons are selected. Setting up for display. All of this is fairly boilerplate code for the tableView:cellForRow: message. The big difference here is that we are not fetching the row contents from a database, but hard-coding the button title. This can easily be internationalized as well. 
  - (UITableViewCell *)  tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {       static NSString *CellIdentifier = @"Cell";       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];     if (cell == nil) {         cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];     }       // are we setting up our button section?     if(indexPath.section == 1) {         switch(indexPath.row) {             case 0: cell.text = @"Clear History"; break;             case 1: cell.text =@"Clear Cookies"; break;             case 2: cell.text = @"Clear Cache"; break;         }     }     else {         // do whatever for the other sections     }       return cell;  }  
For cell-based buttons, you want to avoid using the accessory view, like putting in a detailed disclosure button or the checkmark. Having these items on a "button" will be confusing.Handling actions. All you do here is figure out which "button" was hit and do whatever it is you need to do. Also notice the code to turn the highlight off. 
  - (void)  tableView:(UITableView *) aTableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath  {     // remove the row highlight     [aTableView deselectRowAtIndexPath:indexPath animated:YES];       // Is this section our "button" section?     if(indexPath.section == 1) {         switch(indexPath.row) {             case 0: [self doClearHistory]; break;             case 1: [self doClearCookies]; break;             case 2: [self doClearCache]; break;         }           return;     }     else {         // do other stuff...     }  }  

Real Buttons

Real buttons offer all the advantages you get with a real button. For one thing, the size of the button can be fully customizable. This allows you to have two buttons side by side, as in this example from showing detailed info of a contact: 
You can't have two table cells side by side like that, so these have to be buttons. You'll note that these rounded corners match the rounded corners of the table cells. I think these buttons use the normal RoundedRect button, as opposed to custom buttons. Custom buttons are mostly needed when you want a background color other than white. But if all you need are plain white backgrounds, you can use the RoundedRect buttons. Which leads to the other advantage of using real buttons: better control over background colors. Setting a background color in a grouped table cell is difficult. Just simply setting the background property to a color is not enough, as the rounded corners do not get the color. The only solution I've seen to this problem is a complicated bit of code to color in the curved corners (as demonstrated here). You also don't get the cool gradients as you see in the two red buttons on the top two examples.
There are probably other advantages to using real buttons, but to me these are enough to force me to use buttons sometimes. 

Implementing

So how are UIButtons integrated into a UITableView? Again, there may be several ways, but I find the easiest is to sneak the buttons into a section header. Each section can have a header view. In this view is where you put your UIButton objects. The section itself has no data rows, only a header. So what I do is accommodate for one extra section in my table, but return 0 for the number of rows. 
  - (NSInteger)  numberOfSectionsInTableView:(UITableView *)aTableView  {     // return the number of sections the data is organized in, plus 1 for the button     return 2 + 1;  }  
Assuming you want your button at the end of the table, you would use code like this to return the number of rows: 
  - (NSInteger)  tableView:(UITableView*) aTableView numberOfRowsInSection:(NSInteger) sectionNum  {     if(sectionNum == 3) {         // this is our button section         return 0;     }     else {         // do whatever, according to the data     }  }  
Now we have to create our buttons. This is done in the tableView:viewForHeaderInSection: 
  - (UIView *)  tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)sectionNum  {     if(sectionNum == 2) {         // create the parent view that will hold 1 or more buttons         UIView* v = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)];            // create the button object         UIButton* b = [UIButton buttonWithType:UIButtonTypeCustom];         [b setBackgroundImage:[[UIImage imageNamed:@"redbutton.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0] forState:UIControlStateNormal];         [b setBackgroundImage:[[UIImage imageNamed:@"bluebutton.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0] forState:UIControlStateHighlighted];           b.frame = CGRectMake(10.0, 0.0, 300.0, 44.0);         [b setTitle:@"Button Title" forState:UIControlStateNormal];           // give it a tag in case you need it later         b.tag = 1;           // this sets up the callback for when the user hits the button         [b addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];                // add the button to the parent view         [v addSubview:b];           return [v autorelease];     }     else {         // stuff for other sections     }  }    
The values for the frames are specific to portrait mode; landscape mode will need some modifications. To add more buttons in this view, just adjust the y parameter in the frame for the button. I typically add 46.0 from the last one. This code makes use of two button images: 
 
 I got these from user "hakimny" from this thread. Creating these aren't hard. (I have posted an article on how to create simple background images like this in Inkscape.)
If you want to create a button with a white background, then you don't need to create a custom button. You can create a RoundedRect button that will look more like the surrounding cells, like you saw above. In this case, your button creation is simply: 
b = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
You don't need to set the background images. If you want to create two side by side buttons, all you have to do is monkey around with the frames of the buttons so that they are side by side instead of on top of each other. There is one gotcha I have discovered using this mechanism, and I think it is an SDK bug. If your table takes up more than one screen and you have to scroll to see your button, some of the button may remain hidden under the tab bar or tool bar. You won't be able to scroll the entire header view into view. This is especially noticeable if you have 2 or more buttons stacked on top of each other. I think Cocoa Touch is confused by there being no data rows, or maybe it can't quite figure out how high the header view is. So the way around it is to tell how high your view is. Once you do this, the view is no longer partially hidden: 
  - (CGFloat)  tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)sectionNum  {     return 46.0;  }    
Of course, if you have more buttons in this section, you would return the appropriate height. There you have a quick tutorial on putting buttons in a table. How you choose which mechanism to use is up to you. My own guidelines are as follows: 
  1. If I want a simple black on white button: use a cell-based button
  2. If I need a colored button: use a real button
  3. If I want multiple buttons per row: use real buttons

6 comments:

  1. Hi JES

    I am trying to implement the code in viewForHeaderInSection....

    The button goes in ok but the titles for the other sections are missing. You have added a comment '// stuff for other sections'

    Can you expand on what should go there. I have tried to return a view with a label in it but things dont look so good. The label overlaps and the cells dont space out anymore.

    Thanks

    Reply
  2. Ah, good question! I also ran into this problem, but forgot to mention it. For other sections where I didn't want to return a specific view for, I returned nil. So for the "stuff for other sections" should simply be:

    return nil;

    Please give this a try and let me know if it works for you. If it does, I will update the article.

    Thanks!

    Reply
  3. works for me

    Reply
  4. Awesome post dude - really really helpful. This seems to be the cleanest way to pull this off in a UITableView.

    I was banging my head against the wall on the opacity of the edges of the buttons UNTIL I read closely when you said to EXPORT the button bitmap image from Inkscape. I was 'saving as' a PNG and it was looking like complete crap.

    Thanks again! -jeff

    Reply
  5. Nice work. Thanks.

    I am having a problem where the button is not firing every time and the blue background is not shown on highlight.

    Any thoughs?

    Reply
    Replies
    1. I had this problem it was because i didnt have the code below set. make sure you add your 

      if (sectionNum == x) // x should be the section header you have the button on..
      - (CGFloat)
      tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)sectionNum
      {
      return 46.0;
      }

Wednesday, January 30, 2013

Customize that UIViewCell – Part 1: Using Interface Builder http://www.iphonedevcentral.com/customize-that-uiviewcell-part-1-using-interface-builder/

http://www.iphonedevcentral.com/customize-that-uiviewcell-part-1-using-interface-builder/

Customize that UIViewCell – Part 1: Using Interface Builder

If you followed my first tutorial on UITableView (link | source code), you now have a very simple app that shows a list of DVD titles and clicking any of the titles shows you a detail view page with more information about the DVD.  That's all nice but we really want to make it a little bit prettier. We could display the length of each movie right on the listing page. Also, we have this coverImage field in our data set, let's use it.

What we want is for our home screen to look like this:

tutorial006

We can accomplish that by customizing UITableViewCell. There are 2 ways of going about it:

  1. Using Interface Builder
  2. Programmatically

In reality, you can also choose a hybrid approach where you create some UI elements in the Interface Builder and some programmatically.

Which option to choose?

The two approaches both bring some advantages and disadvantages with them.

Interface Builder

If you decide to go the Interface Builder route, you'll find it very easy to create and customize your cells. Any subsequent edits can also be done quite easily since you're simply rearranging elements visually. The downside is speed and performance since the system needs to render each view in a cell individually. If your table view has thousands of rows in it, this may/may not affect the performance of your app, depending how complicated your cell is.

Programmatically

This one involves a lot more work. You are responsible for creating each UI element by hand in the code. That can be very tedious and any edits you need to make in the future require code changes. Also, you'll need to set up all the autosizing masks yourself. The upside is performance. Since the system will draw each cell as one view, the performance gain can be very significant.

Ok, let's get to it…

1. Subclass UITableViewCell

Create a Cocoa Touch Class file and make it a subclass of UITableViewCell. Let's name it DVDListingViewCell.m. We'll use this class as a placeholder for our labels and the cover image. In DVDListingViewCell.h add the following code:

@interface DVDListingViewCell : UITableViewCell {      IBOutlet UILabel *titleLabel;      IBOutlet UIImageView *coverImageView;      IBOutlet UILabel *featureLengthLabel;  }     @property (nonatomic, retain) UILabel *titleLabel;  @property (nonatomic, retain) UILabel *featureLengthLabel;  @property (nonatomic, retain) UIImageView *coverImageView;     @end

We use the IBOutlet annotation here to later let Interface Builder know we want to connect these properties with the actual UI elements we'll lay out.

We also need synthesize the properties we've just defined. This will create all setters and getters for us. Add this toDVDListingViewCell.m right below the @implementation directive.

@synthesize titleLabel, featureLengthLabel, coverImageView;

2. Design the cell in Interface Builder

In Xcode, double-click on any of the nib files (they should all be listed under NIB Files magic folder). Once in Interface Builder, chooseNew… from the File menu. You should be presented a dialog with several templates in it. From the Cocoa Touch category on the left, choose Empty.

tutorial007

You should now see an "Untitled" window with File's Owner and First Responder in it. One thing missing right now is the actual cell view, let's add it. From the Library window (Tools -> Library) locate Table View Cell. Drag it to the "Untitled" window. You should now see something like this:

tutorial008

Double clicking on the Table View Cell object will open up the actual cell view where we're going to add our UI elements. Make the cell 120 pixels in height (you change the dimensions under the size tab in the properties window or by pressing Command  + 3). Drag a couple Lables and an Image View to the cell to lay it out as shown below. Once done, save the file as DVDListingView. Make sure to save the file in your project directory and check the checkbox when prompted if you want to add the file into your project.

tutorial009

3. Prepare the RootViewController

Return back to Xcode and open up your RootViewController.h header file. We will add a cell instance variable of type DVDListingViewCell that we've created earlier. We will use this cell to actually draw on the screen. Modify your header file to make it look like this:

@interface RootViewController : UITableViewController {      DvdLibraryDao *dao;         IBOutlet DVDListingViewCell *_cell;  }

You may notice the IBOutlet annotation again. That is because we will be connecting this variable to the actual cell we created in Interface Builder.

Let's switch to the implementation file of our RootViewController (RootViewController.m). You may remember the methodcellForRowAtIndexPath from the first tutorial. That's the method that controls what cell is drawn at which row. We'll want our cell to be a DVDListingViewCell so let's modify the current version of it to this:

  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {         static NSString *CellIdentifier = @"LibraryListingCell";         DVDListingViewCell *cell = (DVDListingViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];      if (cell == nil) {          [[NSBundle mainBundle] loadNibNamed:@"DVDListingView" owner:self options:nil];          cell = [_cell autorelease];          _cell = nil;      }         cell.titleLabel.text = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"title"];      cell.featureLengthLabel.text = [NSString stringWithFormat:@"%@ minutes",                                      [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"featureLength"]];      cell.coverImageView.image = [UIImage                                   imageNamed:[[dao libraryItemAtIndex:indexPath.row] valueForKey:@"coverImage"]];         return cell;  }

There are few things going on so let's analyze them line by line.

Line #5 was changed to initialize the cell local variable to the DVDListingViewCell instead of the generic UITableViewCell.

Lines #6-#10 contain the meat of the cell creation. It first loads the nib file we created. You can see we're setting the owner to self. That is because the _cell instance variable will get initialized via the nib file, which I'm going to cover a little later.

And finally, Lines #12-#15 assign proper values to the labels and image view in our custom cell.

4. Connect everything in Interface Builder

Return back to Interface Builder and click on the File's Owner icon. Open up the Identity Inspector (Tools -> Identity Inspector) and look at the Class drop-down menu. Locate RootViewController and select it. In the same window, you should now see the _cell instance variable that belongs to RootViewController. When the nib file is loaded, we'll want the cell we designed in Interface Builder to be assigned to our _cell. Let's do that next.

Open up Connections Inspector (Tools -> Connections Inspector) with File's Owner icon still selected. You should see our _cell in theOutlets section. Next to it is a little hollow circle that turns into a plus (+) sign when you hover it. Click on the circle and drag over to the Listing View Cell window. When you drag over it, the cell should highlight with a label that says "Listing View Cell." Release the mouse to complete the connection (the cell will blink).

tutorial010

Note: There is an alternate way of creating the connection; Click on the File Owner's icon while pressing down the Control key and Ctrl-drag to the Listing View Cell icon. A little black pop-up window "Outlets" will appear. Select _cell and let go of the mouse.

tutorial011

Now let's connect our two labels and the image view. Highlight the Listing View Icon and open up Identity Inspector (Command+4). Under the Class drop-down find and select our DVDListingViewCell. Once done, you should see all the outlets we defined earlier in theDVDListingViewCell class: coverImageView, featureLengthLabel and titleLabel. Open up Connections Inspector (Command+2) and check out the Outlets section. Just as before, drag a connection from the hollow circle next to titleLabel to the "My DVD" label,featureLengthLabel to the feature length label and finally coverImageView to the UIImageView object in our Listing View Cell.

tutorial012

Alternatively, you can Control-drag from the Listing View Cell icon to the Listing View Cell window and connect the three objects that way.

tutorial013Save all your changes and return back to Xcode.

5. Set the cell height in RootViewController

After you've saved your changes in Interface Builder and return back to Xcode, go ahead and run the project. You'll see that everything works well except one thing – the cells are all crammed together.

tutorial014

This is because we need to explicitly set the height of cells in each row when it differs from the default. We can correct that by implementing the heightForRowAtIndexPath delegate method in the RootViewController.m file.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {      return 120.0;  }

Rerun your project and you should now see the cells correctly sized and looking good.

tutorial006

Conclusion

Remember that this is just one of a couple ways to customize your cells. You can do all of this by hand, programmatically which is more work but may result in a better performance. We will cover that in the second part of this tutorial.

You can download the complete source code to this tutorial here: My DVD Library Xcode Project 02.