【问题标题】:How to wrap a text on a UIButton in swift如何快速在 UIButton 上包装文本
【发布时间】:2023-04-01 18:17:01
【问题描述】:

我尝试在按钮上换行如下:

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)

【问题讨论】:

    标签: ios swift uibutton uilabel


    【解决方案1】:

    需要在 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;
    

    【讨论】:

    • 谢谢,但是:这不会换行。在我的情况下,像“这是一个非常长的文本”这样的文本将被缩短为“这是一个非常长的文本”。
    • @user1344545 你在 StoryBoard 中使用 AutoLayout 吗?
    • 没有。我喜欢在运行时用上面的代码做所有事情。
    • 完美。非常感谢您的努力!
    • 对于 Swift 2.1+ 版本,使用 programCell.room.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
    【解决方案2】:

    斯威夫特 4

    要通过用“...”替换文本的中间来缩短文本,您应该使用 NSLineBreakMode.byWordWrapping:

    nextButton.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
    

    要通过将文本末尾替换为“...”来缩短文本,您应该使用 NSLineBreakMode.byTruncatingTail:

    nextButton.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
    

    要查看可用包装模式的完整列表,请查看 NSLineBreakMode 文档:https://developer.apple.com/documentation/appkit/nslinebreakmode

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多