分段控制仅在首次按下时起作用

时间:2019-06-09 11:21:19

标签: swift xcode background controls

我想提供更改应用程序背景的选项。 当我只想更改背景颜色时,一切工作正常。但是我必须使用背景图像。 我正在使用下面的代码

导入UIKit

ContainerController类:UIViewController {

var isRaindrops = false
var Background:String = "UIImage(named: \"Background\")"

override func viewDidLoad() {
    super.viewDidLoad()
    BackgroundSwitch()
    self.view.backgroundColor = .white
}

func BackgroundSwitch() {
    let items = ["Gradient", "Raindrops"]
    let segmentedControl = UISegmentedControl(items: items)
    segmentedControl.translatesAutoresizingMaskIntoConstraints = false
    segmentedControl.frame = CGRect(x: 20, y: self.view.frame.height * 0.2 + 50, width: self.view.frame.width - 40, height: 40)
    segmentedControl.selectedSegmentIndex = 0
    segmentedControl.tintColor = UIColor.black
    segmentedControl.addTarget(self, action: #selector(segmentedControlInAction(sender:)), for: UIControl.Event.valueChanged)
    self.view.addSubview(segmentedControl)
}

@objc func segmentedControlInAction(sender:UISegmentedControl) {

    let index = sender.selectedSegmentIndex

    switch index {
    case 0:
        print("Gradient")
        Background = "Background"
        print(Background)
        //            self.view.backgroundColor = .red
        BackgroundSetup()
    case 1:
        (print("Raindrops"))
        Background = "Raindrops"
        print(Background)
        //            self.view.backgroundColor = .blue
        BackgroundSetup()
    default:
        print("default")
        break
    }
}

func BackgroundSetup() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: Background)
    self.view.insertSubview(backgroundImage, at: 0)
    //        self.view.backgroundColor = Background
}

}

使用我目前的代码,只有当我第一次点击“雨滴”字段时,背景才会改变。

1 个答案:

答案 0 :(得分:0)

我有一个分段的表视图,我同时使用大小写开关和下面的样式。

    if  sender.selectedSegmentIndex == 0
    {
       print("Gradient")
    Background = "Background"
    print(Background)
    BackgroundSetup()
    }
    if  sender.selectedSegmentIndex == 1
    {
       (print("Raindrops"))
    Background = "Raindrops"
    print(Background)
    BackgroundSetup()
    }