ios - Swift将带有 subview 的UIView添加到titleView
<p><p>我想自定义我的导航栏,并在导航栏的标题 View 中插入一个带有两个 subview 的 UIView。
不幸的是, subview 没有显示。
你知道为什么吗?</p>
<pre><code> let titleContainer = UIView()
titleContainer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
let searchIcon = UIButton()
searchIcon.setImage(UIImage(named: "search_icon"), for: UIControlState.normal)
searchIcon.layer.frame = CGRect(x: 0, y: (UIScreen.main.bounds.size.height - 28) / 2, width: 28, height: 28)
titleContainer.addSubview(searchIcon)
let titleLabel = UILabel()
titleLabel.frame = CGRect(x: 28, y: UIScreen.main.bounds.size.height, width: UIScreen.main.bounds.size.width-28, height: UIScreen.main.bounds.size.height)
titleLabel.textColor = UIColor(red:255, green:255, blue:255, alpha:1.0)
titleContainer.addSubview(self.titleLabel)
self.navigationItem.titleView = titleContainer
</code></pre>
<p>问题和预期解决方案:</p>
<p> <a href="/image/5x36e.jpg" rel="noreferrer noopener nofollow"><img src="/image/5x36e.jpg" alt="enter image description here"/></a> </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>为什么将所有元素的<code>height</code>用作<code>UIScreen.main.bounds.size.height</code>?请尝试以下代码。 </p>
<p>附:我已经更改了 <code>searchIcon</code> 的颜色,因为我没有图像并更改了标签文本的颜色并添加了一些文本以使其可见。</p>
<pre><code> let titleContainer = UIView()
titleContainer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 45)
let searchIcon = UIButton()
//searchIcon.setImage(UIImage(named: "search_icon"), for: UIControlState.normal)
searchIcon.backgroundColor = UIColor.red
searchIcon.layer.frame = CGRect(x: 0, y: 8, width: 28, height: 28)
titleContainer.addSubview(searchIcon)
let titleLabel = UILabel()
titleLabel.frame = CGRect(x: 28, y: 8, width: UIScreen.main.bounds.size.width-28, height: 30)
titleLabel.textColor = UIColor.blue//(red:255, green:255, blue:255, alpha:1.0)
titleContainer.addSubview(titleLabel)
titleLabel.text = "Sample Text"
self.navigationItem.titleView = titleContainer
</code></pre>
<p>这是上面代码的截图:</p>
<p> <a href="/image/9f16A.png" rel="noreferrer noopener nofollow"><img src="/image/9f16A.png" alt="enter image description here"/></a> </p>
<p>请根据您的要求相应地更改 x,y。</p></p>
<p style="font-size: 20px;">关于ios - Swift将带有 subview 的UIView添加到titleView,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/49795351/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/49795351/
</a>
</p>
页:
[1]