【问题标题】:Swift button created programmatically needs to have 2 lines for title以编程方式创建的 Swift 按钮需要有 2 行标题
【发布时间】:2016-05-17 09:50:51
【问题描述】:

我正在像这样以编程方式创建按钮:

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

有人可以帮忙吗?

【问题讨论】:

    标签: ios iphone xcode swift uibutton


    【解决方案1】:

    你可以使用 "\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)
    
    }
    

    【讨论】:

    • 我以前不知道按钮的标题,它来自服务器,我不知道在哪里介绍\n
    • 在这种情况下,您必须通过来自服务器的数据动态计算 UIButton 的宽度并保持 numberOfLines = 0 否则您可以制作一个技巧,使用 UIView 与 textView / label 交互 false 和按钮按钮然后按照您必须为 UIView 设置框架的服务器数据,也使 UIView 的 cliptoBounds 为 true。
    • 你找到解决办法了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多