Я пытаюсь создать UIButton в Swift, который имеет два разных setTitles или только два набора текста в нем. Возможно ли это? Если не самый лучший вариант, как сделать кнопку, в ней есть два разных заголовка? Причина, по которой я спрашиваю, заключается в том, что я занимаюсь двумя разными запросами, в которых есть данные, показывающие описание работы и компанию. Я могу только установить имя задания с помощью setTitle, но я не знаю, как также ввести название компании в ту же самую кнопку. Вот визуальное представление о том, чего я пытаюсь достичь. Все поможет спасибо!Как вы помещаете два разных текста в UIButton
ответ
Единственный пример у меня есть для вас это подкласс OS X NSButton, но изменения в UIButton не должно быть трудно.
Обратите внимание, что код drawRect аналогичен тому, как вы делали это в NSView (или UIView). Из фотографии, которую вы опубликовали, я думаю, вы уже знаете, как это сделать.
Код:
import Foundation
import AppKit
class WispSquareButton : NSButton
{
var buttonTitle:String = String();
// *************************************************** Draw Rect ******************************************************
override func drawRect(dirtyRect:NSRect)
{
let context = NSGraphicsContext.currentContext()!.CGContext // Get the context
let rgbColorspace:CGColorSpaceRef = CGColorSpaceCreateDeviceRGB() // Define a color space variable
let nsBounds:NSRect = self.bounds // Get the bounds
let cgBounds:CGRect = NSRectToCGRect(nsBounds) // Sets the graphics bounds
// Top Side Color
CGContextSetRGBFillColor(context, 0.41568627, 0.69803922, 0.95686275, 1.0)
CGContextMoveToPoint(context, 0.0, 0.0)
CGContextAddLineToPoint(context, cgBounds.size.width, 0.0)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.95, cgBounds.size.height * 0.15)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.05, cgBounds.size.height * 0.15)
CGContextAddLineToPoint(context, 0.0, 0.0)
CGContextFillPath(context)
// Right Side
CGContextSetRGBFillColor(context, 0.03529412, 0.20784314, 0.38823529, 1.0)
CGContextMoveToPoint(context, cgBounds.size.width, 0.0)
CGContextAddLineToPoint(context, cgBounds.size.width, cgBounds.size.height)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.95, cgBounds.size.height * 0.85)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.95, cgBounds.size.height * 0.15)
CGContextAddLineToPoint(context, cgBounds.size.width, 0.0)
CGContextFillPath(context)
// Left Side
CGContextSetRGBFillColor(context, 0.41568627, 0.69803922, 0.95686275, 1.0)
CGContextMoveToPoint(context, 0.0, 0.0);
CGContextAddLineToPoint(context, cgBounds.size.width * 0.05, cgBounds.size.height * 0.15)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.05, cgBounds.size.height * 0.85)
CGContextAddLineToPoint(context, 0.0, cgBounds.size.height);
CGContextAddLineToPoint(context, 0.0, 0.0)
CGContextFillPath(context)
// Bottom Side
CGContextSetRGBFillColor(context, 0.03529412, 0.20784314, 0.38823529, 1.0)
CGContextMoveToPoint(context, 0.0, cgBounds.size.height)
CGContextAddLineToPoint(context, cgBounds.size.width, cgBounds.size.height)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.95, cgBounds.size.height * 0.85)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.05, cgBounds.size.height * 0.85)
CGContextAddLineToPoint(context, 0.0, cgBounds.size.height)
CGContextFillPath(context)
// Center
CGContextSetRGBFillColor(context, 0.24117647, 0.53333333, 0.82941176, 1.0)
CGContextMoveToPoint(context, cgBounds.size.width * 0.05, cgBounds.size.height * 0.15)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.95, cgBounds.size.height * 0.15)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.95, cgBounds.size.height * 0.85)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.05, cgBounds.size.height * 0.85)
CGContextAddLineToPoint(context, cgBounds.size.width * 0.05, cgBounds.size.height * 0.15)
CGContextFillPath(context);
if(buttonTitle != "")
{
// ********************************************* Set up the Text
let textSize:CGFloat = cgBounds.size.height * 0.65
let textCenterY:CGFloat = cgBounds.size.height/2.0
let boundsCenterX:CGFloat = cgBounds.size.width/2.0
// Set the text matrix.
let textTransform:CGAffineTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0)
CGContextSetTextMatrix(context, textTransform)
// Create a color that will be added as an attribute to the attrString for button text.
let buttonTextColorComponents:[CGFloat] = [ 0.0, 0.0, 0.0, 1.0 ]
let buttonTextColor:CGColorRef = CGColorCreate(rgbColorspace, buttonTextColorComponents)
// Create a color that will be added as an attribute to the attrString for invisible text.
let invisibleTextColorComponents:[CGFloat] = [ 0.0, 0.0, 0.0, 0.0 ];
let invisibleColor:CGColorRef = CGColorCreate(rgbColorspace, invisibleTextColorComponents);
// Create a font for text.
let stringFontName:CFStringRef = CFStringCreateWithCString(kCFAllocatorDefault, "AppleCasual", kCFStringEncodingASCII)
let stringFont:CTFontRef = CTFontCreateWithName(stringFontName, textSize, nil)
// Create a mutable attributed string with a max length of 0 for normal text.
var attrString:CFMutableAttributedStringRef = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0)
// Create a path which will bound the area where you will be drawing text.
var invisibleTextPath:CGMutablePathRef = CGPathCreateMutable()
// Create a path which will bound the area where you will be drawing text.
var buttonTextPath:CGMutablePathRef = CGPathCreateMutable()
// Center the Title
// Get Title Length
var titleLength:CFIndex = CFStringGetLength(buttonTitle)
// Measure the string length
var invisibleTextBounds:CGRect = CGRectMake(0.0, 0.0, cgBounds.size.width * 2.0, textSize * 1.3)
CGPathAddRect(invisibleTextPath, nil, invisibleTextBounds)
// Copy the title into attrString
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), buttonTitle)
// Set the color and font of the invisibleText
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, titleLength), kCTForegroundColorAttributeName, invisibleColor)
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, titleLength), kCTFontAttributeName, stringFont)
// Create the framesetter with the attributed string.
var framesetter:CTFramesetterRef = CTFramesetterCreateWithAttributedString(attrString);
var frame:CTFrameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), invisibleTextPath, nil);
// Draw the invisible string
CTFrameDraw(frame, context);
var endingTextPoint:CGPoint = CGContextGetTextPosition(context);
// Draw the Visible Text
// Set a rectangular path.
var textBounds:CGRect = CGRectMake(boundsCenterX - (endingTextPoint.x/2.0), textCenterY, cgBounds.size.width, textSize * 1.3)
CGPathAddRect(buttonTextPath, nil, textBounds)
// Copy the textString into attrString
CFAttributedStringReplaceString (attrString, CFRangeMake(0, titleLength), buttonTitle)
// Set the color and font.
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, titleLength), kCTForegroundColorAttributeName, buttonTextColor)
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, titleLength), kCTFontAttributeName, stringFont)
// Create the framesetter with the attributed string.
framesetter = CTFramesetterCreateWithAttributedString(attrString)
// Create a frame.
frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), buttonTextPath, nil)
// Draw the specified frame in the given context.
CTFrameDraw(frame, context);
}
CGContextFlush(context);
}
// ***************************************************** Set Title ****************************************************
func setTitle(aString:String)
{
buttonTitle = aString;
}
}
Я использую кнопку перетаскивания пользовательского вида в окно, и в инспекторе идентичности установлен класс мнения, чтобы «WispSquareButton». Я объявляю IBOutlet к виду:
@IBOutlet var wispSquareButton:WispSquareButton!
И подключить его в IB.
Чтобы установить заголовок кнопки я использую:
wispSquareButton.setTitle("Square Button")
wispSquareButton.display()
Это то, что кнопка выглядит следующим образом:
Чтобы нарисовать вторую строку текста я мог бы добавить дополнительный переменный экземпляр :
var buttonTitle:String = String()
var buttonTitle2:String = String()
Изменить функцию setTitle чтобы:
func setTitle(aString:String, aString2:String)
{
buttonTitle = aString;
buttonTitle2 = aString2
}
и в функции DrawRect повторить рисунок кода buttonTitle для buttonTitle2 (изменение его расположение, конечно). Я также могу изменить все атрибуты шрифта (стиль, размер и цвет шрифта) для buttonTitle2.
Спасибо! Это именно то, что мне нужно! – Tom
- 1. HTML5: Как вы помещаете фиксированный ввод текста через центрирующий холст?
- 2. Как вы помещаете такой сеанс в массив
- 3. Вы помещаете NSFetchRequest в cellForRowAtIndexPath?
- 4. Как вы помещаете UIKit в приложение iOS?
- 5. Как вы помещаете содержимое BufferedReader в строку?
- 6. Как вы помещаете объект в другой поток?
- 7. Как вы помещаете BufferedImage в ByteBuffer?
- 8. Как вы помещаете массив в объект?
- 9. Как вы помещаете {и} в строку формата
- 10. как вы помещаете php в HTML5
- 11. Как вы помещаете ObservableCollection в текстовый блок
- 12. Где вы помещаете файл dotcloud.yml?
- 13. Как вы помещаете текст под другим текстом?
- 14. Вы помещаете Frames в mainloop() в tkinter?
- 15. Как установить два цвета в фон UIButton
- 16. Вы помещаете сборки в репозиторий исходного кода?
- 17. Вы помещаете свои индексы в исходный контроль?
- 18. Вы помещаете «авторские права» в свой код?
- 19. Где вы помещаете классы неконтроллеров в codeigniter?
- 20. Где вы помещаете загруженные файлы в android
- 21. В MVC, где вы помещаете пользовательский класс?
- 22. Выровняйте два разных текста на одной строке в iphone sdk
- 23. Где вы помещаете свои словарные данные?
- 24. Как вы помещаете текстовые поля html edit в php
- 25. Установить выравнивание изображения в UIButton для разных размеров текста
- 26. Как установить два разных цвета текста в TextView в XML?
- 27. Как вы помещаете метод подкласса в суперклассы JLabel?
- 28. Как вы помещаете такие строки, как в веб-сайте ImpactChallenge
- 29. Как вы помещаете XML-значение в массив в PHP?
- 30. Как вы помещаете инструкцию охраны в функцию в Swift?
Вместо того, чтобы пытаться использовать метод setTitle стандартной кнопки, вы можете создать пользовательскую кнопку, которая является подклассом UIbutton. Затем вы можете сделать все, что хотите, в методе drawRect, включая рисование текста в разных местах с помощью множества шрифтов. – jwlaughton
Thats довольно аккуратный Я никогда не знал этого! Можете ли вы привести мне пример? Я все еще участвую, потому что быстрый для меня новый. – Tom