2017-09-21 37 views
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)") 

} 

我在做什麼錯在這裏?

回答

0

(1)當然,他們不匹配,因爲他們有不同的超級視圖。 (查看按鈕)??

(2)看起來像你期待佈局對齊。 UIImageView的contentMode通常具有不同的效果,具體取決於其幀大小和圖像大小。如果您想更改圖像位置,請改爲更新imageEdgeInsets。

+0

公平點(1)LOL。所以我在這個例子中使用'button.imageView?.contentMode = .center'是不正確的?將圖像定位到按鈕內部左側或右側的唯一方法是使用插頁手動進行定位? – sconewolf