カスタムUIButton画像がボタンでサイズ変更されないのはなぜですか?
ビューモードをScaletoFill in Interface Builderに設定しましたが、UIImageViewイメージとは異なり、その設定を尊重しません。
私は間違った場所を見ていますか、それとも不可能ですか?
カスタムUIButton画像がボタンでサイズ変更されないのはなぜですか?
ビューモードをScaletoFill in Interface Builderに設定しましたが、UIImageViewイメージとは異なり、その設定を尊重しません。
私は間違った場所を見ていますか、それとも不可能ですか?
これはあなたが求めているものではないかもしれませんが、背景画像は拡大縮小されます。
これを試して:
[button setImage:image forState:UIControlStateNormal];
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
Swiftの場合:
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
これは古いことは知っていますが、正解は、コンテンツモードをUIButton内にある「非表示」のUIImageViewに設定する必要があるということだと思います。
button.imageView.contentMode = UIViewContentModeScaleAspectFill;
これにより、次のように設定された画像の画像ビューのコンテンツモードが変更されます。
[button setImage:yourAwesomeImage forState:UIControlStateNormal];
//Or any other state
(デザインからまたはコードから):
[ポイント#3の場合:水平および垂直の配置をUIControlContentHorizontalAlignmentFillおよびUIControlContentVericalAlignmentFillに変更]
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
InterfaceBuilder
UIButtonsの画像をInterfaceBuilderのUIViewsと同じように拡大縮小するには、次の手順に従います。
UIButtonを選択し、IdentityInspectorからユーザー定義のランタイム属性に以下を追加します。
imageView.contentMode番号1
ここで、numberはcontentModeの列挙数です。例:
0 = Scale to fill
1 = Aspect Fit
2 = Aspect Fill
etc..
次に、UIButtonの属性エディタを開き、[コントロール]で、水平方向と垂直方向の両方で[配置]を[塗りつぶし](右側の最後のボタン)に設定します。
SWIFT 3
次のコードでこれを行うこともできることに注意してください。
button.imageView?.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
この投稿を更新すると、Swift5の完全な回答になります。
//Set button's image
let image = UIImage(systemName: "heart.fill") //Your image here
button.setImage(image, for: .normal)
//Optional: Remove background image if you added one on accident
button.setBackgroundImage(nil, for: .normal)
//Optional: Set button's title (displayed next to button's image)
button.setTitle(nil, for: .normal)
//The button's "content" includes the title label and image
//So we set the button's content to fill the button
//If title label is nil, the content will only show the image
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
//Set button's image to desired content mode (aspectFit avoids distortion)
//This restricts the image from resizing to fill the entire content area
button.imageView?.contentMode = .scaleAspectFit
InterfaceBuilderのClipsubviewsプロパティをtrueに設定してみてください。
お役に立てば幸いです。
Swift 2.1でこれまでに見つけた最善の解決策は、次のとおりです。
self.imageButton.imageView?.clipsToBounds = true
self.imageButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
これにより、画像が拡大縮小され、imageViewにアスペクトが収まります。
実際のUIimageviewを取得し、その上にUIbuttonを配置し、レイアウトメニューを使用して戻るように設定するだけです。次に、画像を適切に拡大縮小できます。