我尝试将文本包装在按钮上,如下所示:
nextButton=UIButton(frame: CGRectMake(buttonHWidth, textHeigth, buttonHWidth, buttonHeigth));
nextButton.backgroundColor = UIColor.lightGrayColor()
nextButton.setTitle("", forState: UIControlState.Normal)
nextButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
nextButton.tag = 22;
label_nextButton = UILabel(frame: CGRectMake(buttonHWidth, textHeigth, buttonHWidth, buttonHeigth));
label_nextButton.textAlignment = NSTextAlignment.Center;
label_nextButton.numberOfLines = 2;
label_nextButton.font = UIFont.systemFontOfSize(16.0);
label_nextButton.text = "Prss next Press next";
label_nextButton.textColor=UIColor.blackColor();
nextButton.addSubview(label_nextButton);
self.view.addSubview(nextButton);
我可以看到设备上的按钮,但我看不到任何文字。
我做错了什么?或者可以在不向按钮添加标签的情况下完成此操作? 谢谢你的帮助。
插图。它看起来像:
刚做的时候:
nextButton.setTitle("this is a very very long text", forState: UIControlState.Normal)
答案 0 :(得分:8)
您需要在setTitle方法中编写文本:
nextButton.setTitle("This is the very very long text!", forState: UIControlState.Normal)
将行数和换行模式设置为标题标签:
nextButton.titleLabel.numberOfLines = 0; // Dynamic number of lines
nextButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
更新到Swift 4
nextButton.titleLabel.numberOfLines = 0; // Dynamic number of lines
nextButton.titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping;
答案 1 :(得分:2)
Swift 4
要通过用“...”替换文本中间来缩短文本,您应该使用NSLineBreakMode.byWordWrapping:
nextButton.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
要通过用“...”替换文本末尾来缩短文本,您应该使用NSLineBreakMode.byTruncatingTail:
nextButton.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
要查看可用包装模式的完整列表,请查看NSLineBreakMode文档:https://developer.apple.com/documentation/appkit/nslinebreakmode