Swift3如何为UISegmentedControl设置默认文本颜色?

时间:2017-03-08 09:39:49

标签: iphone xcode8 ios10 uisegmentedcontrol swift3.0.2

我想为UISegmentedControl的文本和背景设置颜色。所以我要设置四种颜色,文本和背景的默认和选定颜色。

我可以使用tintColorbackgroundColor来设置背景。但是如何设置默认文本颜色,与色调颜色不一样?

注意:这里是swift3而不是旧语言。我是ios的初学者,我刚从swift3开始,没有前一种语言的经验。

任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:4)

 //ProfilePage     
 loginFB(){
    this.usersService
        .registerUserFb()
        .then(()=>{
             this.usersService.getUserFacebook().subscribe((userObject) => {
                this.user = userObject;
             });
        });
 }


//users.services.ts
registerUserFb(){
    return new Promise(resolve => {
      Facebook.login(['email']).then((response) => {
         Facebook.getLoginStatus().then((response) => {

            if(response.status == 'connected'){
               this.checkIfUserExists(response.authResponse.userID);
               resolve();
            }

         });
      });
    });
}

答案 1 :(得分:2)

快速4 代码为您的UISegmentedControl(在下面的示例中为sc)更新文本颜色:

// selected option color
sc.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.green], for: .selected)

// color of other options
sc.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .normal)

答案 2 :(得分:1)

customSC.backgroundColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)
customSC.tintColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)

答案 3 :(得分:1)

这是可行的:

    //default background color
    customSC.backgroundColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)

    //selected background color
    customSC.tintColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)

    //selected title text color
    customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.selected)

    //default title text color
    customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.darkGray], for: UIControlState.normal)

答案 4 :(得分:1)

Swift 4.2 +

segmentedControl.tintColor = .black //background
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)