Если вы не хотите использовать какой-либо объект, вы все равно можете использовать setattr() внутри вашего текущего модуля:
import sys
current_module = module = sys.modules[__name__] # i.e the "file" where your code is written
setattr(current_module, 'variable_name', 15) # 15 is the value you assign to the var
print(variable_name) # >>> 15, created from a string
Есть два вопроса.
Мне было интересно, можно ли создать UIButton с двумя строками текста
blockquote>Это возможно с помощью раскадровки или программным способом.
Раскадровка:
Измените «Режим прерывания строки» на обертку символов и используйте клавишу Alt / Option + Enter, чтобы ввести новую строку в поле Title UIButton.
[/g0]
Программно:
override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping; }
Мне нужна каждая строка, чтобы иметь другой размер шрифта 1
blockquote>В худшем случае вы можете использовать собственный класс
UIButton
и добавить в него две метки.Лучше всего использовать
NSMutableAttributedString
. Обратите внимание, что это может быть достигнуто только программным способом.@IBOutlet weak var btnTwoLine: UIButton? override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //applying the line break mode btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping; var buttonText: NSString = "hello\nthere" //getting the range to separate the button title strings var newlineRange: NSRange = buttonText.rangeOfString("\n") //getting both substrings var substring1: NSString = "" var substring2: NSString = "" if(newlineRange.location != NSNotFound) { substring1 = buttonText.substringToIndex(newlineRange.location) substring2 = buttonText.substringFromIndex(newlineRange.location) } //assigning diffrent fonts to both substrings let font:UIFont? = UIFont(name: "Arial", size: 17.0) let attrString = NSMutableAttributedString( string: substring1 as String, attributes: NSDictionary( object: font!, forKey: NSFontAttributeName) as [NSObject : AnyObject]) let font1:UIFont? = UIFont(name: "Arial", size: 11.0) let attrString1 = NSMutableAttributedString( string: substring2 as String, attributes: NSDictionary( object: font1!, forKey: NSFontAttributeName) as [NSObject : AnyObject]) //appending both attributed strings attrString.appendAttributedString(attrString1) //assigning the resultant attributed strings to the button btnTwoLine?.setAttributedTitle(attrString, forState: UIControlState.Normal) }
Выход
[/g1]
Я исправил это, и мое решение было только в раскадровке.
Изменения:
Он добавлен в Identity Inspector -> Пользовательские атрибуты времени выполнения (эти KeyPaths):
Пользовательские атрибуты времени выполнения
Он добавлен в инспектор атрибутов:
измените разрыв строки на обертку символа, выберите свою кнопку и инспектор атрибутов перейдите к разрыву строки и измените ее на обертку символа
[/g0]
Синтаксис SWIFT 3
let str = NSMutableAttributedString(string: "First line\nSecond Line")
str.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 17), range: NSMakeRange(0, 10))
str.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(11, 11))
button.setAttributedTitle(str, for: .normal)
Я заметил проблему в большинстве решений, которая при создании режима разрыва строки на «Wrap Wrap» вторая строка будет выровнена по первой строке
Чтобы сделать все линии центрированными. просто измените заголовок From Plain to Attributed, а затем вы можете сделать каждую линию по центру
Я искал почти ту же тему, за исключением того, что мне не нужны два разных размера шрифта. Если кто-то ищет простое решение:
let button = UIButton()
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .byWordWrapping
button.setTitle("Foo\nBar", for: .normal)
button.titleLabel?.textAlignment = .center
button.sizeToFit()
button.addTarget(self, action: #selector(rightBarButtonTapped), for: .allEvents)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
Вам нужно сделать часть этого кода. вы не можете установить 2 разных шрифта в IB. В дополнение к изменению режима разрыва строки на обертку символов вам нужно что-то подобное, чтобы установить заголовок,
override func viewDidLoad() {
super.viewDidLoad()
var str = NSMutableAttributedString(string: "First line\nSecond Line")
str.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(17), range: NSMakeRange(0, 10))
str.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: NSMakeRange(11, 11))
button.setAttributedTitle(str, forState: .Normal)
}
Один из способов сделать это с ярлыками, я думаю. Я сделал это, и он работает нормально. Я мог бы создать это как UIButton, а затем выставить ярлыки, я думаю. Я не знаю, имеет ли это смысл.
let firstLabel = UILabel()
firstLabel.backgroundColor = UIColor.lightGrayColor()
firstLabel.text = "Hi"
firstLabel.textColor = UIColor.blueColor()
firstLabel.textAlignment = NSTextAlignment.Center
firstLabel.frame = CGRectMake(0, testButton.frame.height * 0.25, testButton.frame.width, testButton.frame.height * 0.2)
testButton.addSubview(firstLabel)
let secondLabel = UILabel()
secondLabel.backgroundColor = UIColor.lightGrayColor()
secondLabel.textColor = UIColor.blueColor()
secondLabel.font = UIFont(name: "Arial", size: 12)
secondLabel.text = "There"
secondLabel.textAlignment = NSTextAlignment.Center
secondLabel.frame = CGRectMake(0, testButton.frame.height * 0.5, testButton.frame.width, testButton.frame.height * 0.2)
testButton.addSubview(secondLabel)