簡體   English   中英

UIBarButtonItem動作選擇器ios11

[英]UIBarButtonItem action selector ios11

UIButton *rideButton = [UIButton buttonWithType:UIButtonTypeCustom];
rideButton.titleLabel.font = CUSTOM_BUTTON_FONT;
[rideButton setTitleColor:[UIColor CUSTOM_BUTTON_TITLE_COLOR1] forState:UIControlStateNormal];
[rideButton setTitleColor:[UIColor CUSTOM_BUTTON_TITLE_COLOR2] forState:UIControlStateHighlighted];
[rideButton setTitle:@"Ride" forState:UIControlStateNormal];
[rideButton addTarget:self action:@selector(rideButtonClicked) forControlEvents:UIControlEventTouchUpInside];
CGSize s1 = [rideButton.titleLabel.text sizeWithFont:rideButton.titleLabel.font];
rideButton.frame = (CGRect) {
    .size.width = (s1.width+rideBarButtonGap)>100?100:(s1.width+rideBarButtonGap),
        .size.height = s1.height + rideBarButtonGap
};

rideButton.backgroundColor = [UIColor redColor];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0)
{
    [[rideButton.widthAnchor constraintEqualToConstant:rideButton.frame.size.width] setActive:YES];
    [[rideButton.heightAnchor constraintEqualToConstant:rideButton.frame.size.height] setActive:YES];
}

UIBarButtonItem *rideBarButton= [[UIBarButtonItem alloc] initWithCustomView:rideButton];
self.navigationItem.rightBarButtonItem = rideBarButton;

這是我創建自定義UIBarButtonItem的代碼。 我已將背景色設置為紅色,只是為了查看按鈕的邊界。 背景顏色在文本外部看起來很完美,但是我無法正確單擊按鈕。 僅當選擇“ Ri”時,按鈕的動作才會觸發。 如果選擇“ de”,則不調用該函數。 它僅在iOS 11中發生。我添加了寬度和高度約束來解決此問題,但沒有任何更改。

編輯:當我增加widthAnchor的寬度時,我能夠達到我想要的,但是按鈕向左移動,並且按鈕和屏幕之間有很多間隙。 所以我嘗試使用rideButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;來對齊內容rideButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight; 盡管內容向右移動,但可單擊區域仍在中間。

嘗試這個:

public extension UIView {
//From iOS 11 -> UIBarButtonItem uses autolayout instead of dealing with frames. so adding contraint for the barbuttonItem
public func applyNavBarConstraints(size: (width: CGFloat, height: CGFloat)) {
    if #available(iOS 11.0, *) {
        let widthConstraint = self.widthAnchor.constraint(equalToConstant: size.width)
        let heightConstraint = self.heightAnchor.constraint(equalToConstant: size.height)
        heightConstraint.isActive = true
        widthConstraint.isActive = true
    }
}}

並如下使用:

rideBarButton.applyNavBarConstraints(size: (width: 50, height: 44)) //expected height and width

這對我有用。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM