设置UIButton的文字、字体、颜色等 |
您所在的位置:网站首页 › 设置按钮的背景色和颜色 › 设置UIButton的文字、字体、颜色等 |
初始化
UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 20)];
[self.view addSubview:cancelButton];
这样初始化的button,文字默认颜色是白色的,所有如果背景也是白色的话,是看不到文字的 设置文字、颜色 cancelButton.titleLabel.textColor = [UIColor greenColor]; cancelButton.titleLabel.text = @"取消"; 使用上面的方式,设置的文字没有效果,无法显示出来,因为titleLabel属性是readonly的,只能读值,不能设值。
类似的还有imageView、currentBackgroundImage等属性。正确的方法是调用 set开头的一些api,比如: [cancelButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal]; [cancelButton setTitle:@"取消" forState:UIControlStateNormal]; 设置文字位置设置文字位置,现设为居左,默认的是居中 cancelButton.titleLabel.textAlignment = UITextAlignmentLeft; 这是不行的,需要如下设置: cancelButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;如果希望文字与边框有边距,则: cancelButton.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);设置背景色 直接设置backgroundColor属性 cancelButton.backgroundColor = [UIColor yellowColor]; 或者 [cancelButton setBackgroundColor:[UIColor yellowColor]]; 它其实就是 backgroundColor属性的getter方法 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |