0
我試圖在UIButton
中居中放置一個圖像,併產生意外的結果。 (1)當我在控制檯中打印按鈕和圖像的中心點時,它們不匹配,但它們應該,不應該嗎? (2)當我將.center
更改爲其他任何內容時,如.left
,圖像仍保留在中心位置。 .center
似乎沒有效果。
在產生意外結果的按鈕中居中放置圖像
func addSearchButton() {
let button = UIButton()
button.frame.size.width = 56
button.frame.size.height = 56
button.frame.origin.y = 20 + 8
button.frame.origin.x = 8
button.imageView?.contentMode = .center
button.backgroundColor = UIColor.green
button.setImage(#imageLiteral(resourceName: "searchIcon"), for: .normal)
button.setImage(#imageLiteral(resourceName: "searchIcon"), for: .highlighted)
button.addTarget(self, action: #selector(openSearch), for: .touchUpInside)
view.addSubview(button)
print("search: \(button.center.x)")
print("search: \(button.imageView!.center.x)")
}
我在做什麼錯在這裏?
公平點(1)LOL。所以我在這個例子中使用'button.imageView?.contentMode = .center'是不正確的?將圖像定位到按鈕內部左側或右側的唯一方法是使用插頁手動進行定位? – sconewolf