Shamsudheen ..
211
有两个问题.
我想知道是否可以用两行文本创建一个UIButton
这可以通过使用故事板或以编程方式实现.
故事板:
将" 换行模式"更改为字符换行或自动换行,并使用Alt/Option + Enter键在UIButton的"标题"字段中输入新行.
编程方式:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping;
}
我需要每一行都有不同的字体大小1
最糟糕的情况是,您可以使用自定义UIButton类并在其中添加两个标签.
更好的方法是,利用NSMutableAttributedString.请注意,这只能通过编程方式实现.
@IBOutlet weak var btnTwoLine: UIButton?
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//applying the line break mode
textResponseButton?.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping;
let buttonText: NSString = "hello\nthere"
//getting the range to separate the button title strings
let newlineRange: NSRange = buttonText.range(of: "\n")
//getting both substrings
var substring1 = ""
var substring2 = ""
if(newlineRange.location != NSNotFound) {
substring1 = buttonText.substring(to: newlineRange.location)
substring2 = buttonText.substring(from: newlineRange.location)
}
//assigning diffrent fonts to both substrings
let font1: UIFont = UIFont(name: "Arial", size: 17.0)!
let attributes1 = [NSMutableAttributedString.Key.font: font1]
let attrString1 = NSMutableAttributedString(string: substring1, attributes: attributes1)
let font2: UIFont = UIFont(name: "Arial", size: 11.0)!
let attributes2 = [NSMutableAttributedString.Key.font: font2]
let attrString2 = NSMutableAttributedString(string: substring2, attributes: attributes2)
//appending both attributed strings
attrString1.append(attrString2)
//assigning the resultant attributed strings to the button
textResponseButton?.setAttributedTitle(attrString1, for: [])
}
产量
您可以将两个行文本都居中对齐。编写以下代码btnTwoLine?.titleLabel?.textAlignment = NSTextAlignment.Center或使用情节提要文件执行此操作(控制部分-> Alignment) (3认同)
效果很好。我现在想知道是否有任何方法可以使文本在每行上居中,以及是否有办法在两行之间插入更多的空间。 (2认同)