简体   繁体   中英

How to set background color of UIView inside of UIStackView?

I am making a Detail screen which has several nested views in the Storyboard View Controller: ScrollView > UIView > StackView > 5 UI Views. Each UI view is a different section that contains labels and edit texts.

When I set the background of one of the UIViews in the storyboard it changes but does not reflect this change when I run the emulator or on an iPad.

Below is a picture with the emulator view on the left and the Storyboard in Xcode on the right. You can see that the emulator shows no background color on the nested UIView while the Storyboard does.

Emulator vs Storyboard

Because it was asked for here is the full Storyboard. It is tough to see but it is a tab view controller connected to three split view controllers.

Full Storyboard

By testing with only specific views I have narrowed it down to the UIStackView holding the 5 UIViews that causes the problem. I have tried attaching a controller and changing the color in code but nothing I've tried seems to change it.

class ClientDetailViewController: UIViewController {

@IBOutlet weak var basicInfoUIView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    basicInfoUIView.backgroundColor = UIColor.init(displayP3Red: 22, green: 22, blue: 22, alpha: 0.5)
    }
}

I expect for each section (UIView) to be a dark gray color but instead they are all clear so the scrollview background color can be seen.

UIStackView doesn't allow changing background color:

The UIStackView is a nonrendering subclass of UIView; that is, it does not provide any user interface of its own. Instead, it just manages the position and size of its arranged views. As a result, some properties (like backgroundColor) have no effect on the stack view. Similarly, you cannot override layerClass, draw( :), or draw( :in:).

(from UIStackView )

A simple workaround is to add another UIView behind the stack view, setup the constraints to match the position and size of the stack view (equal top, left, right, bottom) and change background color of that view.

在此处输入图片说明 I think first you should give different background colors to your ui views then place them. Under a single stack and check whether it is working or not

I have added a screenshot where i first gave background colors to UIviews and then placed them under one stackView but they had those colors unlike you after giving them background color simply from the uielements under the controller on the left pick the Uiviews and place them under stack View

Well, check your color please. 22 should not belong to [0,1].

basicInfoUIView.backgroundColor = UIColor.init(displayP3Red: 22.0 / 255.0, green: 22.0 / 255.0, blue: 22.0 / 255.0, alpha: 0.5)

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