I have a button in my ios project which displays edit profile if the user is the current user and follow if the user is not the current user.

I am setting the titleLabel text programmatically dependant on the above condition. I am also programatically setting the button text to align center.

The problem I'm having is it works perfectly for the edit profile button which appears as it should center aligned but when showing the follow button the word follow is slightly off center to the left and I can't figure out where I'm going wrong.

Here is my code:

 if([userID isEqualToString:credentialID]){
        self.followEditBtn.layer.cornerRadius = 2;
        self.followEditBtn.layer.borderColor = UIColorFromRGB(0xA6B9C1).CGColor;
        self.followEditBtn.layer.borderWidth = 1.0f;
        self.followEditBtn.layer.backgroundColor = UIColorFromRGB(0xF8FBFC).CGColor;
        self.followEditBtn.titleLabel.textColor = UIColorFromRGB(0xA1B1C3);
        self.followEditBtn.titleLabel.text = @"Edit Profile";
        self.followEditBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    } else {
        self.followEditBtn.layer.cornerRadius = 2;
        self.followEditBtn.layer.borderColor = UIColorFromRGB(0x19A548).CGColor;
        self.followEditBtn.layer.borderWidth = 1.0f;
        self.followEditBtn.layer.backgroundColor = [UIColor whiteColor].CGColor;
        self.followEditBtn.titleLabel.textColor = UIColorFromRGB(0x19A548);
        self.followEditBtn.titleLabel.text = @"Follow";
        self.followEditBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    }

And some images of the buttons as you can see the follow text is slightly off center to the left yet the edit profile button is correctly aligned:

enter image description here

enter image description here

有帮助吗?

解决方案

I couldn't reproduce your problem (iOS 6.1 to 7.1). Although I had to make a small change in order to make it work, since it wasn't showing any text. Instead of using:

self.followEditBtn.titleLabel.text = @"Edit Profile";

you should use:

[self.followEditBtn setTitle:@"Follow" forState:UIControlStateNormal];

I'm assuming you're using a UIButtonTypeCustom type UIButton, and having a fixed frame size.

I'd like you to tell me where are you putting this code, and how is this button being initialized.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top