tot*_*ian 61 objective-c ios swift
我在工具栏中有一个按钮.我怎么能抓住它的框架?难道UIBarButtonItem不是有一个frame属性?
Ano*_*dya 89
试试这个;
UIBarButtonItem *item = ... ;
UIView *view = [item valueForKey:@"view"];
CGFloat width;
if(view){
    width=[view frame].size.width;
}
else{
    width=(CGFloat)0.0 ;
}
Mob*_*Mon 19
这种方式最适合我:
UIView *targetView = (UIView *)[yourBarButton performSelector:@selector(view)];
CGRect rect = targetView.frame;
tot*_*ian 12
感谢Anoop Vaidya的建议答案.另一种方法是(让您知道工具栏中按钮的位置)
UIView *view= (UIView *)[self.toolbar.subviews objectAtIndex:0]; // 0 for the first item
CGRect viewframe = view.frame;
Luc*_*nzo 10
使用Swift,如果你需要经常使用条形按钮项,你应该实现这样的扩展:
extension UIBarButtonItem {
    var frame: CGRect? {
        guard let view = self.value(forKey: "view") as? UIView else {
            return nil
        }
        return view.frame
    }
}
然后在您的代码中,您可以轻松访问:
if let frame = self.navigationItem.rightBarButtonItems?.first?.frame {
    // do whatever with frame            
}
Dan*_*ark 10
Oof,在这个帖子中有很多粗略的答案.这是正确的方法:
import UIKit
class ViewController: UIViewController {
    let customButton = UIButton(type: .system)
    override func viewDidLoad() {
        super.viewDidLoad()
        customButton.setImage(UIImage(named: "myImage"), for: .normal)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: customButton)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print(self.customButton.convert(self.customButton.frame, to: nil))
    }
}
这是我在 iOS 11 和 Swift 4 中使用的。没有可选的它可能会更干净一些,但我很安全:
extension UIBarButtonItem {
    var view: UIView? {
        return perform(#selector(getter: UIViewController.view)).takeRetainedValue() as? UIView
    }
}
和用法:
if let barButtonFrame = myBarButtonItem.view?.frame {
    // etc...
}
| 归档时间: | 
 | 
| 查看次数: | 51812 次 | 
| 最近记录: |