简体   繁体   中英

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

You should edit directly the button, not the titleLabel , like this:

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM