ios - Swift 4 - 添加到 UINavigationBar 时无法控制 UIButton 的大小
<p><p>我一直在尝试构建自定义 UINavigationBar,但我的 button.frame 输入没有任何效果。</p>
<pre><code>override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "I_sent"), for: .normal)
button.addTarget(self, action: #selector(action), for: .touchUpInside)
// This doesn't seem to have an effect:
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
button.contentMode = .scaleAspectFit
let item = UIBarButtonItem(customView: button)
navigationItem.rightBarButtonItem = item
}
@objc func action() {
print("Action")
}
</code></pre>
<p>上面的代码在运行时是这样的:</p>
<p> <a href="/image/PNAVe.png" rel="noreferrer noopener nofollow"><img src="/image/PNAVe.png" alt=""/></a> </p>
<p>但我试图让它看起来像这样:</p>
<p> <a href="/image/3txqe.png" rel="noreferrer noopener nofollow"><img src="/image/3txqe.png" alt=""/></a> </p>
<p>非常感谢任何帮助!</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>将约束添加到 <code>UIButton</code> 为:</p>
<pre><code>button.widthAnchor.constraint(equalToConstant: button.frame.size.width).isActive = true
button.heightAnchor.constraint(equalToConstant: button.frame.size.height).isActive = true
</code></pre>
<p>希望对你有帮助!</p></p>
<p style="font-size: 20px;">关于ios - Swift 4 - 添加到 UINavigationBar 时无法控制 UIButton 的大小,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/46701332/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/46701332/
</a>
</p>
页:
[1]