无法在swift中更改循环内的textColor和字体大小

时间:2015-05-06 13:35:31

标签: ios swift uibutton for-in-loop

我不知道为什么字体大小和文字颜色在循环中没有任何效果......任何人都有帮助? 这是我的代码:

var buttons = ["N","F","S","D","C","A","R"]


    for button in buttons
        {

            var Button:UIButton = UIButton()

            Button = UIButton(frame: CGRect(x:10, y: 20, width: 80, height: 80))
            Button.frame.origin = ButtonPosition
            ButtonPosition.x = ButtonPosition.x + buttonIncrement
            Button.layer.cornerRadius = 3
            Button.clipsToBounds = true
            Button.backgroundColor = UIColor.groupTableViewBackgroundColor()
            Button.setTitle("\(button)", forState: UIControlState.Normal)
            Button.titleLabel?.text = "\(button)"
            Button.titleLabel?.font = UIFont(name:"Chalkboard SE Regular", size: 30)
            Button.titleLabel?.textColor = UIColor.blackColor()
            Button.setBackgroundImage(UIImage.imageWithColor(UIColor.colorWithHex("#b8b4af", alpha: 0.5)), forState: .Highlighted)

            Button.addTarget(self, action: "check:", forControlEvents: UIControlEvents.TouchUpInside)

        buttonView.addSubview(Button)  

    }

    return buttonView

2 个答案:

答案 0 :(得分:0)

您应该直接修改按钮,而不是titleLabel,如下所示:

Button.setTitle("\(button)", forState: .Normal)
Button.setTitleColor(UIColor.blackColor(), forState: .Normal)

答案 1 :(得分:0)

首先删除行Button.titleLabel?.text = "\(button)"。 这个就足够了Button.setTitle("\(button)", forState: UIControlState.Normal)

然后您应该使用按钮中的setTitleColor方法进行更改。 Button.setTitleColor(UIColor. blackColor(), forState: UIControlState.Normal)

最后你在字体名称中犯了一个错误: Button.titleLabel?.font = UIFont(name:"ChalkboardSE-Regular", size: 30.0)

就是这样!