barbuttonitem 文字换行_Swift - UIButton有两行文字

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认同)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值