Search code examples
iosswiftuibuttonfor-in-loop

Cannot change textColor and font size inside the loop in swift


I have no idea why the font size and text Color doesn't takes any effect in the loop...anyone help?? Here is my code:

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

Solution

  • First remove the line Button.titleLabel?.text = "\(button)". This one is enough Button.setTitle("\(button)", forState: UIControlState.Normal).

    Then you should use setTitleColor method from a button to change it. Button.setTitleColor(UIColor. blackColor(), forState: UIControlState.Normal)

    Finally you made a mistake in the name of your font : Button.titleLabel?.font = UIFont(name:"ChalkboardSE-Regular", size: 30.0)

    That's it!