我正在以编程方式创建按钮:
let stage: Stages = stagesObjectsArray[i]
let button = UIButton(type: .Custom) as UIButton
button.setTitle(stage.name, forState: .Normal)
button.sizeToFit()
button.frame.origin = buttonPosition
let buttonIncrement = button.frame.size.width + padding.width
buttonPosition.x = buttonPosition.x + buttonIncrement
button.backgroundColor = UIColor.blackColor()
button.titleLabel?.font = UIFont(name: "", size: widthOfScreen/3.2)
button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
button.tag = stage.id
button.addTarget(self, action: #selector(GamesAllViewController.buttonPressedTopMenu(_:)), forControlEvents: .TouchUpInside)
buttonView.addSubview(button)
我想要实现的内容,如果按钮的宽度变得太大(例如超过屏幕宽度的一半),无法弄清楚如何在2行上设置按钮的标题。
我在这个主题上发现了一些问题,但他们都认为他们知道按钮的标题,而在我的情况下,它是动态的,我不知道它可能是什么。
我试过这段代码,但没有改变:
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel!.numberOfLines = 2
有人可以帮忙吗?
答案 0 :(得分:0)
您可以使用" \ n"和NoOFLines为0
试试这段代码
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
let button = UIButton(type: .Custom) as UIButton
button.setTitle("Line 1\nLine 2", forState: .Normal)
button.sizeToFit()
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel!.numberOfLines = 0
button.titleLabel!.textAlignment = NSTextAlignment.Center
button.frame = CGRectMake(20, 100, 280, 40)
button.titleLabel?.textColor = UIColor.redColor()
button.backgroundColor = UIColor.blackColor()
button.addTarget(self, action: "methodName:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}